public static void main(String[] args) {
int[] a = {7, 5, 3, 1, 21, 6, 4, 8, 7,10, 17, 2, 9, 11};
quickSort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
long[] b = {1, 2, 3, 4, 7, 3, 5, 10, 23, 89, 44};
int i = Arrays.binarySearch(b, 4);
System.out.println(i);
}
//二分查询
public static int binarySearch(long[] a, long key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
long midVal = a[mid];
if (midVal < key) {
low = mid + 1;
} else if (midVal > key) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
//快速排序
public static void quickSort(int[] a, int left, int right) {
int i = left;
int j = right;
int pivot = a[left];
while (i < j) {
while (i < j && a[j] >= pivot) //从右往左找比基准值小的数
j--;
if (i < j) {
int temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
}
while (i < j && a[i] <= pivot) //从左往右找比基准值大的数
i++;
if (i < j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
j--;
}
}
if (i > left) {
quickSort(a, left, i - 1);
}
if (j < right) {
quickSort(a, i + 1, right);
}
}