代码:
import java.util.Arrays; | |
public class Test { | |
private static void bubbleSort(Integer[] arr){ | |
for(int i=0;i<arr.length;i++){ | |
for(int j=0;j<arr.length - 1 - i;j++){ | |
if(arr[j] > arr[j+1]){ | |
int temp = arr[j+1]; | |
arr[j+1] = arr[j]; | |
arr[j] = temp; | |
} | |
} | |
} | |
System.out.println("Bubble sort result: " + Arrays.toString(arr)); | |
} | |
private static int binarySearch(int searchVal, int[] searchArr){ | |
int begin = 0; | |
int end = searchArr.length - 1; | |
while(begin < end){ | |
int mid = begin + (end - begin) / 2; | |
if(searchVal > searchArr[mid]){ | |
begin = mid + 1; | |
}else if(searchVal < searchArr[mid]){ | |
end = mid - 1; | |
}else{ | |
System.out.println("Binary search result: " + begin); | |
return begin; | |
} | |
} | |
return 0; | |
} | |
private static void multiplicationTable(){ | |
for(int i=1;i<=9;i++){ | |
for(int j=1;j<=9;j++){ | |
if(i<=j){ | |
System.out.print(i + " * " + j + " = " + i*j + " "); | |
} | |
} | |
System.out.println(); | |
} | |
} | |
public static void main(String[] args) { | |
Integer[] arr = {8, 9, 4, 2, 1, 0, 5, 7}; | |
bubbleSort(arr); | |
int searchVal = 3; | |
int[] searchArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; | |
int position = binarySearch(searchVal, searchArr); | |
multiplicationTable(); | |
} | |
} |
def binary_search(search_val, search_array): | |
begin = 0 | |
end = len(search_array) - 1 | |
while begin < end: | |
mid = begin + (end - begin) // 2 | |
if search_val < search_array[mid]: | |
end = mid - 1 | |
elif search_val > search_array[mid]: | |
begin = mid + 1 | |
else: | |
print(f"Binary search result: {begin}") | |
return begin | |
def bubble_sort(array): | |
arr_length = len(array) | |
for i in range(arr_length): | |
step_length = arr_length - 1 - i | |
for j in range(step_length): | |
if array[j] > array[j + 1]: | |
array[j], array[j + 1] = array[j+1], array[j] | |
print(f"Bubble sort result: {array}") | |
def multiplication_table(): | |
for i in range(1, 10): | |
for j in range(1, 10): | |
if i <= j: | |
print("{:>2} * {:>2} = {:>2} ".format(i, j, i*j), end='') | |
print() | |
if __name__ == '__main__': | |
binary_search(3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) | |
bubble_sort([8, 9, 4, 2, 1, 0, 5, 7]) | |
multiplication_table() |