【发布时间】:2011-01-19 23:31:03
【问题描述】:
我有以下Quicksort 始终选择子序列的第一个元素作为其枢轴:
void qqsort(int array[], int start, int end) {
int i = start; // index of left-to-right scan
int k = end; // index of right-to-left scan
if (end - start >= 1) { // check that there are at least two elements to sort
int pivot = array[start]; // set the pivot as the first element in the partition
while (k > i) { // while the scan indices from left and right have not met,
while (array[i] <= pivot && i <= end && k > i) // from the left, look for the first element greater than the pivot
i++;
while (array[k] > pivot && k >= start && k >= i) // from the right, look for the first element not greater than the pivot
k--;
if (k > i) // if the left seekindex is still smaller than the right index, swap the corresponding elements
swap(array, i, k);
}
swap(array, start, k); // after the indices have crossed, swap the last element in the left partition with the pivot
qqsort(array, start, k - 1); // quicksort the left partition
qqsort(array, k + 1, end); // quicksort the right partition
} else { // if there is only one element in the partition, do not do any sorting
return;
}
}
现在您可以看到,此算法始终将第一个元素作为枢轴:int pivot = array[start];
我想修改此算法,使其始终使用子序列的最后一个元素而不是第一个元素,因为我想分析两种实现的物理运行时间。
我尝试将行 int pivot = array[start]; 更改为 int pivot = array[end]; 但算法随后输出了一个未排序的序列:
//Changes: int pivot = array[end];
unsorted: {5 4 3 2 1}
*sorted*: {1 2 5 4 3}
为了测试另一个枢轴,我也尝试使用子序列的中心元素,但算法仍然失败:
//Changes: int pivot = array[(start + end) / 2];
unsorted: {5 3 4 2 1}
*sorted*: {3 2 4 1 5}
谁能帮我正确理解这个算法,并告诉我需要做哪些改变才能成功地让这个实现总是选择子序列的最后一个元素作为枢轴?
【问题讨论】:
-
你的牙套发生了一些奇怪的事情。似乎有些被注释掉了,有些被删除了,还有一个留在里面。尝试重新发布您的代码。
-
@colithium - 谢谢你……没注意到;现在修好了。
标签: algorithm sorting pivot quicksort