二分法
https://blog.csdn.net/qq_42676052/article/details/84258755
快速排序
https://blog.csdn.net/as02446418/article/details/47395867
import java.util.Arrays;
/**
- @author Pstart
- @create 2019-11-09 10:12
/
/ - 快速排序
- 以基准量为起点,从数组最右边开始找小于基准量的数
- 从数组最左边找大于基准量的数
- 彼此替换,在相遇点
- 将值与基准量比较,小于基准量则替换
- 对原基准量的左边和右边递归使用quickSortLeft方法
- 右边选择的是中间值做基准量
- */
public class QuickSort {
public static void quickSortLeft(int[] arr, int min, int max) {
int pull, push, temp, base;
if (min > max) {
return;
}
pull = max;
push = min;
base = arr[min];
while (push < pull) {
for (; base <= arr[pull] && push < pull; ) {
pull--;
}
for (; base >= arr[push] && push < pull; ) {
push++;
}
if (push < pull) {
temp = arr[pull];
arr[pull] = arr[push];
arr[push] = temp;
}
}
arr[min] = arr[push];
arr[push] = base;
//左
quickSortLeft(arr, min, pull - 1);
//右
quickSortLeft(arr, pull + 1, max);
}
//折半查找
public static int binary(int[] arr, int arrayLength, int key) {
int init = 0;
int max = arrayLength;
while (init <= max) {//1,2,3,4,5 找1,找5
int middle = (init + max) / 2;
if (key == arr[middle]) {
return middle;
} else if (key < arr[middle]) {
max = middle - 1;//1/2=0
} else {
init = middle + 1;
}
}
return -1;
}
//二分查找的递归写法
public static int binaryRecursive(int[] arr, int init, int arrayLength, int key) {
int middle = (init + arrayLength) / 2;
if (init>arrayLength){
return -1;
}
if (key < arr[middle]) {
return binaryRecursive(arr, init, arrayLength - 1, key);
} else if (key > arr[middle]) {
return binaryRecursive(arr, init, arrayLength + 1, key);
} else{
return middle;
}
}
public static void main(String[] args) {
int[] arr = {3, 8, 0, 7, -9, 2, 9, -1, 20};
int mark = 0;
int arrLength = arr.length - 1;
quickSortLeft(arr, mark, arrLength);
System.out.println("快速排序后-" + Arrays.toString(arr));
if (binary(arr, arrLength, -1) != -1) {
System.out.println("二分法查找值(-1)索引=" + binary(arr, arrLength, -1));
System.out.println("递归二分法查找值(-1)索引=" + binaryRecursive(arr, mark, arrLength, -1));
}
}
}