【发布时间】:2018-04-13 07:05:29
【问题描述】:
我的任务是对各种排序算法的不同运行时间进行基准测试。我能够运行我的所有算法。但是,在处理大型数组时遇到了溢出问题。用于快速排序的递归可能太深了,但我不确定如何简化它。任何帮助将非常感激。这是我的构造函数和快速排序的示例:
/**
* constructor for sorting
*/
Sorting(int size)
{
arraySize = size;
theArray = new int[size];
}
/**
* creates a random array
*/
public void generateRandomArray()
{
for (int i = 0; i < theArray.length; i++) {
theArray[i] = (int)(Math.random());
}
itemsInArray = arraySize - 1;
}
/**
* creates an array that is almost sorted
*/
public void almostSortedArray()
{
for (int i=0; i <theArray.length; i++)
{
theArray[i] = i;
}
theArray[theArray.length/2] = (int)(Math.random());
itemsInArray = arraySize -1;
}
/**
* quick sort
*/
public void quickSort(int left, int right) {
int pivot = theArray[right/2];
int pivotLocation = partitionArray(left, right, pivot);
if (right - left <= 0)
return;
else {
quickSort(left, pivotLocation - 1);
quickSort(pivotLocation + 1, right);
}
}
public int partitionArray(int left, int right, int pivot) {
int leftPointer = left -1 ;
int rightPointer = right;
while (true) {
while (theArray[++leftPointer] < pivot)
;
while (rightPointer > 0 && theArray[--rightPointer] > pivot)
;
if (leftPointer >= rightPointer) {
break;
} else {
swapValues(leftPointer, rightPointer);
}
}
swapValues(leftPointer, right);
return leftPointer;
}
/**
* Swaps higher value for
*/
public void swapValues(int indexOne, int indexTwo) {
int temp = theArray[indexOne];
theArray[indexOne] = theArray[indexTwo];
theArray[indexTwo] = temp;
}
【问题讨论】:
-
是这样吗?看起来它忽略了左边。
int pivot = theArray[right/2]; -
对于错误,至少您应该发布堆栈跟踪并指出哪一行存在问题。此外,最好提供一个最小、完整、可验证的示例idownvotedbecau.se/noexceptiondetails
标签: java recursion stack-overflow quicksort