【发布时间】:2018-10-21 06:45:57
【问题描述】:
import java.util.Random;
public class Quicksort {
private int partition(int arr[], int first, int last) {
int pivot = arr[last]; //Using last element as pivot
int i = (first-1);//index of smaller element
for (int j = first; j < last; j++) {
//if current element is smaller than or equal to pivot
//then swap the elements
if (arr[j] <= pivot) {
i++;
//swapping occurs here
//make a temp variable to the first element
//swap arr[j] and arr[i]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
//i++;
}
}
int temp = arr[i+1];
arr[i+1] = arr[last];
arr[last] = temp;
return i+1;
}
private void quickSort(int arr[], int first, int last) {
if (first < last) {
int pivindex = partition(arr, first, last);
quickSort(arr, first, pivindex-1);
quickSort(arr, pivindex+1, last);
}
}
public void sort(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}
public static int[] getRandoms(int count) {
return new Random().ints().limit(count).toArray();
}
public static void main(String[] args) {
Quicksort fix = new Quicksort();
int[] randoms = getRandoms(40000);
double startTime = System.currentTimeMillis();
fix.sort(randoms);
double endTime = System.currentTimeMillis();
System.out.println("Performance Time on Random Data:" + (endTime - startTime));
//Benchmarking quicksort on already sorted data
startTime = System.currentTimeMillis();
fix.sort(randoms);
endTime = System.currentTimeMillis();
System.out.println("Performance Time on Sorted Data:" + (endTime - startTime));
}
}
我不完全确定为什么会收到 Stackoverflow 错误。当我只排序一次时,代码运行良好,但是,如果我尝试对相同的数据进行两次排序,那就是我得到错误的时候。
我了解 Stackoverflow 错误的发生是因为使用递归存在问题。在这种情况下,我的错误来自
线程“主”java.lang.StackOverflowError 中的异常 在 quicksort.Quicksort.quickSort(Quicksort.java:36)
这是..
if (first < last) {
int pivindex = partition(arr, first, last);
quickSort(arr, first, pivindex-1);
quickSort(arr, pivindex+1, last);
}
【问题讨论】:
-
也许检查一下给定的数组索引是否已排序?
-
它实际上是对数据进行排序吗?您说“运行良好”,但您的意思是它可以正常退出吗?
-
@mackycheese21 当我说它运行良好时,我的意思是如果我使用一个较小的数组,我可以打印出来查看,它会打印出来排序。对 40,000 个随机整数进行排序也是如此,直到我尝试对已经排序的数组进行排序。
标签: java recursion stack-overflow quicksort