目录
二分查找
import java.util.Arrays;
public class BinarySearchTestDrive {
public static int count = 0;
public static int binarySearch(int[] arr, int val) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
count++;
int mid = (left + right) / 2;
if (arr[mid] > val) {
right = mid - 1;
} else if (arr[mid] < val) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = new int[1_0000];
for(int i=0;i<arr.length;i++) {
arr[i] = i;
}
Arrays.sort(arr);
// System.out.println(Arrays.toString(arr);
System.out.println(binarySearch(arr, 9999));
System.out.println(count); //统计出比较的次数
}
}
//输出:9999 14
冒泡排序
public class BubbleSortTestDrive {
public static void bubbleSort(int[] arr) {
boolean flag = true;
for (int i = 0; i < arr.length - 1; i++) {
flag = true;
for (int j = 0; j < arr.length - 1 - i; j++) {
if(arr[j] >arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = false;
}
}
if(flag) {
break;
}
}
}
public static void main(String[] args) {
int[] arr = new int[] {1,5,2,3,6,7,4,0,9};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
}
//输出:[0, 1, 2, 3, 4, 5, 6, 7, 9]
选择排序
import java.util.Arrays;
public class SelectSortTestDrive {
public static void selectSort(int[] arr) {
for(int i=0;i<arr.length-1;i++) {
for(int j=i;j<arr.length;j++) {
if(arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = new int[] {1,5,2,4,6,8,9,7,3};
selectSort(arr);
System.out.println(Arrays.toString(arr));
}
}