快速排序和二分查找(Java)
Posted 飞晨信息
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快速排序和二分查找(Java)相关的知识,希望对你有一定的参考价值。
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);
}
}
}
以上是关于快速排序和二分查找(Java)的主要内容,如果未能解决你的问题,请参考以下文章
Java八股文面试题 基础篇 -- 二分查找算法冒泡排序选择排序插入排序希尔排序快速排序