int[] a = {12, 20, 5, 16, 15, 1, 30, 45, 23, 9};int start = 0;int end = a.length - 1;sort(a, start, end);for (int i = 0; i < a.length; i++) { System.out.PRintln(a[i]);}//////////////////////////////////////////////////////////////////////////////////////public static void sort(int[] a, int low, int high) {// int[] a = {12,20,5,16,15,1,30,45,23,9};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) sort(a, low, start - 1);//左邊序列。第一個索引位置到關鍵值索引-1if (end < high) sort(a, end + 1, high);//右邊序列。從關鍵值索引+1到最后一個} 15912151620233045
新聞熱點
疑難解答