我的任务是对各种排序算法的不同运行时间进行基准测试。我能够运行所有算法。但是,在处理大型数组时遇到溢出问题。用于快速排序的递归可能太深,但我不确定如何简化它。任何帮助将非常感激。以下是我的构造函数示例和快速排序:
/**
* 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;
}
答案 0 :(得分:0)
使用long或BigInteger而不是int。溢出意味着数字大于int可以容纳。
答案 1 :(得分:0)
是arrayIndexOutOfBound还是溢出?查看在while循环中递增leftpointer的代码。假设所有元素都小于pivot,那么你试图访问一个不存在的元素,你应该得到ArrayIndexOutOfBound。对于右指针也一样,你需要在while循环中放入break,如果指针到达右端则循环应该终止。
`public int partitionArray(int left, int right, int pivot) {
int leftPointer = left -1 ;
int rightPointer = right;
while (true) {
while (theArray[++leftPointer] < pivot){
if(leftPointer == rightPointer) break; // Here i think you got IndexOutOfBound
}
while (rightPointer > 0 && theArray[--rightPointer] > pivot)
if(rightPointer == LeftPointer) break;
if (leftPointer >= rightPointer) {
break;
} else {
swapValues(leftPointer, rightPointer);
}
}
swapValues(leftPointer, right);`