我应该实现快速排序赋值和我有几个问题。我的代码运行得比想象的慢得多,我找不到减慢的速度,因为我严格按照我们的教师伪代码。快速排序太慢,ArrayIndexOutOfBoundsError
另外,当我们提交这段代码时,它已经过测试,但是我们看不到测试,它说我得到了一个ArrayIndexOutOfBounds错误,这对我来说没有意义,因为我已经检查了限制是否在正确的范围内。
任何帮助,非常感谢。
public QuickSort() {
rand = new Random();
}
@Override
public void sort(int[] v) {
sort(v, 0, v.length-1);
}
/**
* Sort an array from two set points,
* usually from first index to last.
*/
private void sort(int[] v, int first, int last){
if(first >= last || last <= first || first < 0 || last < 0)
return;
else if(first >= last-10){
Insertionsort.sort(v, first, last);
return;
}
else if(first < last && first >= 0){
int rnd = first+rand.nextInt(last-first+1);
swap(v, rnd, last);
int mid = partition(v, first, last);
sort(v, first, mid-1);
sort(v, mid+1, last);
}
}
/**
* Swaps elements in array around a
* pivot element.
* < pivot to the left
* > pivot to the right
*/
private int partition(int[] v, int first, int last){
int x = v[last];
int i = first-1;
for(int j = first; j<last; j++){
if(v[j] <= x){
i++;
swap(v, i, j);
}
}
swap(v, (i+1), (last));
return (i+1);
}
/**
* Swap two elements in a list
*/
private void swap(int[] v, int a , int b){
int temp = v[a];
v[a] = v[b];
v[b] = temp;
}
我插入排序类:
public class Insertionsort {
public Insertionsort() {}
public static void sort(int[] v, int first, int last){
int j, toInsert;
for (int i = first+1; i < v[last]; i++) {
toInsert = v[i];
j = i;
while (j > 0 && v[j - 1] > toInsert) {
v[j] = v[j - 1];
j--;
}
v[j] = toInsert;
}
}
}
我的父(我们应该实现这个为我们营造了不同版本的快速排序的)
public interface IntSorter {
/**
* Sorts the array into ascending numerical order.
*/
void sort(int[] v);
}
你有自己的测试呢?到目前为止你的测试用例是什么? –
你如何调用'sort'方法,你的输入在哪里? – stjepano
你的测试用例是什么?你可以发布**完整异常堆栈跟踪**。 –