我一直在研究一个需要对选择排序,快速排序和java快速排序(arrays.sort)的经过时间进行实证分析的项目。程序中的一切都运行良好,除非它到达我的用户时创建了快速排序,执行时出现问题并且它给出了堆栈溢出错误。我确定这里有一个递归调用问题,但我不知道在哪里或如何修复它。快速排序方法的代码可以在下面找到。
public void quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
private void quickSort(int[] list, int first, int last) {
if (last > first) {
int pivotIndex = partition(list, first, last);
quickSort(list, first, pivotIndex - 1);
quickSort(list, pivotIndex + 1, last);
}
}
/** Partition the list[first..last] */
private int partition(int[] list, int first, int last) {
int pivot = list[first]; // Choose the first element as the pivot
int low = first + 1; // Index for forward search
int high = last; // Index for backward search
while (high > low) {
// Search forward from left
while (low <= high && list[low] <= pivot)
low++;
// Search backward from right
while (low <= high && list[high] > pivot)
high--;
// Swap two elements in the list
if (high > low) {
int temp = list[high];
list[high] = list[low];
list[low] = temp;
}
}
while (high > first && list[high] >= pivot)
high--;
// Swap pivot with list[high]
if (pivot > list[high]) {
list[first] = list[high];
list[high] = pivot;
return high;
}
else {
return first;
}
}
/*Main*/
public static void main(String[] args) {
Lab5 sortLab = new Lab5 ();
Scanner input = new Scanner(System.in);
int n;
System.out.print("Enter the size of the data set N = ");
n = input.nextInt();
int[] array1 = new int[n];
int[] array2 = new int[n];
int[] array3 = new int[n];
int[] array4 = new int[n];
Random rnd = new Random(System.currentTimeMillis());
for (int i=0; i<array1.length; i++){
if (rnd.nextDouble() < 0.5) // positive integers
array1[i]=(1 + rnd.nextInt(100));
else // negative integers
array1[i]=((1 + rnd.nextInt(100)) * -1);
}//for
for(int i = 0; i < 10; i++){
System.arraycopy(array1, 0, array2, 0, n);
System.arraycopy(array1, 0, array3, 0, n);
//printing nanoseconds only
long startTime = System.nanoTime(); //start clock
sortLab.quickSort(array2);//call method to be measured
long elapsedTime = System.nanoTime() - startTime ; //stop clock - start clock gives elapsed time
System.out.printf("\tTime elapsed for our quick sort: = %f", ((double)elapsedTime)/Math.pow(10,9));
System.arraycopy(array4, 0, array1, 0, n);
System.arraycopy(array4, 0, array2, 0, n);
System.arraycopy(array4, 0, array3, 0, n);
}//for
}//main