我在下面实现了快速排序算法,该数组已排序,但没有退出递归循环。有人可以在下面分析我的快速排序算法并检查我在做什么错吗?
请在下面查看我的代码:
package sort;
import java.util.Arrays;
public class QuickSort {
public int array[];
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
quickSort(0, this.array.length);
}
private void quickSort(int low, int high)
{
if (low < high)
{
int j = partition(low, high);
quickSort(low, j);
quickSort(j+1, high);
}
}
private int partition(int low, int high) {
int pivot = this.array[low];
int i = low;
int j = high;
while (i<j) {
do {
i++;
} while (this.array[i] <= pivot);
do {
j--;
} while (this.array[j] > pivot);
}
swap(low,j);
return j;
}
private void swap(int i, int j) {
int temp = this.array[i];
this.array[i] = this.array[j];
this.array[j] = temp;
}
}
答案 0 :(得分:1)
Hoare分区方案应类似于或类似(使用中间值作为数据透视):
private int partition(int low, int high) {
int pivot = this.array[low+(high-low)/2];
int i = low-1;
int j = high+1;
while (true) {
while (this.array[++i] < pivot); // not <=
while (this.array[--j] > pivot);
if(i >= j)
return j;
swap(i,j);
}
}