我不得不做这个小任务,我必须手工排序一个阵列'像quicksort一样。有一个特定点(递归的)我不确定我的解决方案是什么 对。如果有人能看透这个会很好!
初始序列:7 4 6 8 9 1 3 2
解决方案(i =左索引,x =枢轴,j =右索引): [Pivot-index =(i + j)/ 2]
Sort for positions 0 to 7:
i x j
7 4 6 8 9 1 3 2
(swap 8 and 2)
i j
7 4 6 8 9 1 3 2
i j
7 4 6 2 9 1 3 8
(swap 9 and 3)
i
j
7 4 6 2 3 1 9 8
Sort for positions 0 to 5:
i x j
7 4 6 2 3 1 9 8
(swap 7 and 1)
i j
1 4 6 2 3 7 9 8
(swap 6 and 3)
i
j
1 4 3 2 6 7 9 8
Sort for positions 0 to 3:
i x j
1 4 3 2 6 7 9 8
(swap 4 and 2)
i
j
1 2 3 4 6 7 9 8
Sort for positions 0 to 2:
i x j
1 2 3 4 6 7 9 8
(swap 2 'and' 2)
j i
1 2 3 4 6 7 9 8
Sort for positions 6 to 7 (from first split - not sure here!)
i j
x
1 2 3 4 6 7 9 8
(swap 9 and 8)
j i
1 2 3 4 6 7 8 9
使用过的代码:
public class QuickSort {
public static void sort (int[] a) { // public method
quicksort(a, 0, a.length-1); // starts private method
}
private static void quicksort (int[] a, int left, int right) {
int tmp; // temporary param
int i = left; // left index
int j = right; // right index
int middle = (left + right) / 2; // middle position
int x = a[middle]; // pivot element
do {
while (a[i] < x) i++; // x works as break
while (a[j] > x) j--; // x works as break
if (i <= j) {
tmp = a[i]; // temporary storage
a[i] = a[j]; // a[i] and
a[j] = tmp; // a[j] get swapped
i++;
j--;
}
} while (i <= j);
// all elements on the left side of the array are smaller than
// all elements in the right side of the array
if (left < j) quicksort(a, left, j); // sort left side
if (i < right) quicksort(a, i, right); // sort right side
}
}