【发布时间】:2020-06-18 16:47:00
【问题描述】:
我正在尝试使用递归和几种辅助方法来实现快速排序。当我运行程序时,我收到一条越界消息,告诉我我已经转向数组的索引 -1。任何人都可以提供有关修复我的快速排序方法的建议吗? (这就是问题所在)。我知道我的其他方法是正确的。
示例 {7,6,5,4,3,2,1}
应该是{1,2,3,4,5,6,7}
public static <T extends Comparable<? super T>> void quickSort(T[] a) {
quickSort(a,0,a.length - 1);
}
public static <T extends Comparable<? super T>> void quickSort(T[] a,int start,int end) {
if(start<end) {
int pivotIndex = partition(a, start, end);
quickSort(a,start,pivotIndex-1); // sort left partition
quickSort(a,pivotIndex+1,end); // sort right partition
}
}
public static <T extends Comparable<? super T>> int partition(T[] a, int start, int end) {
int mid =midpoint(start,end);
sortFirstMiddleLast(a,start,mid,end);
swap(a,mid,end-1);
int pivotIndex = end -1 ;
T pivotValue = a[pivotIndex];
int indexFromLeft = start +1 ;
int indexFromRight = end -2;
boolean done = false;
while (!done) {
while (a[indexFromLeft].compareTo(pivotValue)<0) {
indexFromLeft++;
}
while (a[indexFromRight].compareTo(pivotValue)>0) {
indexFromRight--;
}
if (indexFromLeft < indexFromRight) {
swap(a,indexFromLeft,indexFromRight);
indexFromLeft++;
indexFromRight--;
}
else {
done=true;
}
}
swap(a,pivotIndex,indexFromLeft);
pivotIndex=indexFromLeft;
return pivotIndex;
}
public static <T extends Comparable<? super T>> void sortFirstMiddleLast(T[] a, int start, int mid, int end) {
if (a[start].compareTo(a[mid])>0) {
swap(a,start,mid);
}
else if (a[mid].compareTo(a[end])>0) {
swap(a,mid,end);
}
else if (a[start].compareTo(a[end])>0) {
swap(a,start,end);
}
else if(a[start].compareTo(a[mid])>0) {
swap (a,start,mid);
}
}
private static int midpoint(int first, int last) {
return first + (last - first) / 2;
}
private static void swap(Object[] a, int first, int second) {
Object temp = a[first];
a[first] = a[second];
a[second] = temp;
}
【问题讨论】:
-
你还没有分享
swap方法的代码。 -
抱歉,刚刚发布了
-
您需要对内部
while循环之一进行范围检查。查看任何经典实现。 -
@user207421 - 如果未从起始索引对中排除枢轴,则不需要范围检查。