[英]exception in merge for non-iterative mergesort algorithm
I'm trying to create a non-recursive version of MergeSort but for some reason merge is keeping the code from running in its entirety. 我正在尝试创建MergeSort的非递归版本,但由于某些原因,合并使代码无法完整运行。
Mergesort Code: 合并排序代码:
public void mergeSort(int[] input)
{
int n = input.length;
int size;
int l;
for (size = 1; size <= n-1; size = 2*size)
{
for (l = 0; l < n-1; l += 2*size)
{
int m = l + size -1;
int r = minimum(l + 2*size - 1, n-1);
merge(input, l, m, r);
}
}
}
Merge code: 合并代码:
public static void merge(int[] numbers, int low, int middle, int high)
{
// Copy both parts into the helper array
int helper[];
helper = new int[numbers.length];
for (int i = low; i <= high; i++) {
helper[i] = numbers[i];
}
int i = low;
int j = middle + 1;
int k = low;
// Copy the smallest values from either the left or the right side back
// to the original array
while (i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
numbers[k] = helper[i];
i++;
} else {
numbers[k] = helper[j];
j++;
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
numbers[k] = helper[i];
k++;
i++;
}
}
This is how I fill up the input array (which is of size 100): 这就是我填写输入数组(大小为100)的方式:
public static int fillArray()
{
Random r = new Random();
int rand = r.nextInt();
return rand;
}
//followed by these lines of code in the main method:
int[] arr;
arr = new int[100];
for(int i =0; i<arr.length; i++)
{
arr[i] = fillArray();
}
The exception is with numbers[k] = helper[i]
in merge()
. 例外是
merge()
numbers[k] = helper[i]
。
I know that the contents of the input array are fine because I print out the contents of the array before I perform MergeSort on it. 我知道输入数组的内容很好,因为在对它执行MergeSort之前,我先打印出数组的内容。 Does anyone know what the problem is?
有人知道问题出在哪里吗?
You didn't mention what exception you get but I assume its array out of bounds. 您没有提到得到什么异常,但是我认为它的数组超出范围。 What prevents your middle variable from exceeding the size of the array?
是什么阻止您的中间变量超过数组的大小?
while (i <= middle) {
numbers[k] = helper[i];
k++;
i++;
}
Put in debugging prints etc. 放入调试打印等
像这样在mergeSort()
固定m
:
int m = Math.min(l + size - 1, n - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.