//冒泡排序
public static void demo(int[] arr) {
for (int i = 0; i < arr.length - 1; 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(Arrays.toString(arr));
}
//选择排序
public static int[] xzDemo(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
- 二分查找 这个数组必须是排好序的(从大到小或者从小到大)
//二分查找
public static int towDome(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (arr[middle] == key) {
System.out.println(middle);
return middle;
} else if (arr[middle] > key) {
right = middle - 1;
} else {
left = middle + 1;
}
}
return -1;
}