快速排序分为两步:1)分割,2)分别对分割所得两部分进行快速排序
所以重点在于partittion(),下面是java实现
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] array = new int[n];
for (int i = 0; i < array.length; i++) {
array[i] = cin.nextInt();
}
sort(array);
for (int i = 0; i < array.length; i++) {
System.out.printf("%d ", array[i]);
}
// System.out.printf("%n");
cin.close();
}
public static void sort(int[] array){
int head = 0, tail = array.length-1;
quickSort(array, head, tail);
}
public static void quickSort(int[] array, int head, int tail){
if (head >= tail) return;
int mid = partition(array, head, tail);
// mid 认为已经排好位置
quickSort(array, head, mid-1);
quickSort(array, mid+1, tail);
}
public static int partition(int[] array, int head, int tail) {
// low为左指针, high为右指针, 其中high的初值设置有技巧
int low = head, high = tail+1;
// 选定中间值
int midValue = array[low];
while(true){
while(array[++low] < midValue) if(low == tail) break;
while(array[--high] > midValue) if(high == head) break;
if(low >= high) break;
int temp = array[low];
array[low] = array[high];
array[high] = temp;
}
// 因为此时一定有array[high] <= midValue
int temp = array[head];
array[head] = array[high];
array[high] = temp;
return high;
}
}