import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] data = {2, 3, 5, 1, 4, 5, 2, 13, 51, 9, 10, 15, 17, 6, 21, 33, 44, 77, 22};
System.out.println(Arrays.toString(data));
quickSort(data, 0, data.length - 1);
System.out.println(Arrays.toString(data));
int index = binarySearch(data, 4);
System.out.println(index);
}
private static int partition(int[] data, int left, int right) {
int i = left;
int j = right;
//pivot
int pivot = data[left + (right - left) / 2];
//完成一趟排序
while (i <= j) {
//从右往左找到第一个小于pivot的数
while (data[j] > pivot) {
j--;
}
//从左往右找到第一个大于pivot的数
while (data[i] < pivot) {
i++;
}
//交换
if (i <= j) {
int p = data[i];
data[i] = data[j];
data[j] = p;
i++;
j--;
}
}
return i;
}
public static void quickSort(int[] data, int left, int right) {
int index = partition(data, left, right);
if (left < index - 1) {
quickSort(data, left, index - 1);
}
if (index < right) {
quickSort(data, index, right);
}
}
public static int binarySearch(int[] data, int target) {
int left = 0, right = data.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (data[mid] < target) {
left = mid + 1;
}
if (data[mid] >= target) {
right = mid - 1;
}
}
return left;
}
public int binarySearchRecur(int[] data, int target, int left, int right) {
if (left > right) {
return left;
}
int mid = left + (right - left) / 2;
if (data[mid] < target) {
return binarySearchRecur(data, target, mid + 1, right);
} else {
return binarySearchRecur(data, target, left, mid - 1);
}
}
}