public static void main(String[] args) {
int[] a = { 8, 24, 3, 9, 17, 4, 7, 35, 29, 3, 1 };
// 利用遞歸求得1+2+。。。n
quickSort(a, 0, a.length - 1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ",");
}
}
private static void quickSort(int[] a,int low,int high) {
int start = low;
int end = high;
int key = a[low];
//從後到前
while(end>start) {
while(end>start&&a[end]>=key)
end--;
if(a[end]<key) {
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
while(end>start&&a[start]<=key)
start++;
if(a[start]>key) {
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
}
if(start>low) quickSort(a,low,start-1);
if(high>end) quickSort(a, start+1, high);;
}
思路:在前半部分:我們每次取a[low]來作爲key來與其他元素進行比較,先從後到前,大於key保持不變,end--,小於key,進行交換。 再從前往後,同樣的方式。完成所有元素的排序