快速排序
2018-12-18 本文已影响0人
猴子扔飞镖
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));
}
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);
}
}