我的Quicksort算法遇到了一些麻烦。它在没有重复值的数组上运行良好。但是,一旦我有一个2+重复的数组,它就会陷入无限循环。例如,如果我的数组是:
int[] array = {44, 53, 36, 186, 22, 162, 22};
public void quick_sort(int[] data, int low, int high)
{ // 1 or 0 items are sorted by default
if(high - low < 1)
return;
int left = low;
int right = high;
int pivot = data[low + (high - low) / 2];
while(left < right)
{ // Increment left pointer until left >= pivot
while(data[left] < pivot)
left++;
// Increment right pointer until right <= pivot
while(data[right] > pivot)
right--;
// If left <= right; swap values
if(left <= right)
{ int temp = data[right];
data[right] = data[left];
data[left] = temp;
}
}
// quick_sort 'lesser values'
quick_sort(data, low, left - 1);
// quick_sort 'greater values'
quick_sort(data, left + 1, high);
}
提前感谢您的帮助。
解决:
public void quick_sort(int[] data, int low, int high)
{ // 1 or 0 items are sorted by default
if(high - low < 1)
return;
int left = low;
int right = high;
int pivot = data[low + (high - low) / 2];
while(left <= right)
{ // Increment left pointer until left >= pivot
while(data[left] < pivot)
left++;
// Increment right pointer until right <= pivot
while(data[right] > pivot)
right--;
// If left < right; swap values
if(left <= right)
{ int temp = data[left];
data[left] = data[right];
data[right] = temp;
left++;
right--;
}
}
// quick_sort 'lesser values'
quick_sort(data, low, right);
// quick_sort 'greater values'
quick_sort(data, left, high);
}
答案 0 :(得分:2)
好吧,有了重复项,您可以获得(left < right)
但data[left] == pivot == data[right]
。
在这种情况下,你的循环不会向左或向右递增,它只是一次又一次地交换元素......(即使在left==right
时也很有趣“交换”)
答案 1 :(得分:0)
考虑data[left] == data[right] == pivot
时会发生什么。