[英]Mergesort - Stackoverflow when splitting array not in a half
I've a problem. 我有问题 I have to edit the standard mergesort algorithm, changing the ratio between the two halves of the array. 我必须编辑标准mergesort算法,更改数组两半之间的比率。 Standard mergesort splits array in 2. BUT I've to split it with a coefficient. 标准mergesort在2中拆分数组。但是我必须用系数对其进行拆分。
Example: 例:
I've a 10elements array, and i've to split it with a coeff of 0.2. 我有一个10个元素的数组,我必须以0.2的系数进行拆分。 This means that the first time the array is divided in 2 parts: one with 2 elements, the second with 8 elements. 这意味着第一次将数组划分为2个部分:一个包含2个元素,第二个包含8个元素。 Being recursive, this ratio is applied every time I split the array. 由于是递归的,因此每次拆分数组时都会应用此比率。
The problem: 问题:
If the coeff >=0.5 no probs. 如果系数> = 0.5,则没有概率。 If the ratio in <=0.5 every attempt leads to a stackoverflow. 如果比率<= 0.5,则每次尝试都会导致堆栈溢出。
Any help will be kindly appreciated! 任何帮助将不胜感激!
Here the class: 这里的课:
public class Sort {
public static double coeff = 0.2;
public static void mergeSort(int[] a) {
int vectorTemp[];
vectorTemp = new int[a.length];
mergeSort(a, vectorTemp, 0, a.length - 1);
}
private static void mergeSort(int[] a, int[] vectorTemp, int left, int right) {
if (left < right) {
int center = calculateMid(left, right);
mergeSort(a, vectorTemp, left, center);
mergeSort(a, vectorTemp, center + 1, right);
merge(a, vectorTemp, left, center + 1, right);
}
}
private static void merge(int[] a, int[] vectorAux, int posLeft, int posRight, int posEnd) {
int endLeft = posRight - 1;
int posAux = posLeft;
int numElemen = posEnd - posLeft + 1;
while (posLeft <= endLeft && posRight <= posEnd) {
if ((a[ posLeft]) < (a[posRight])) {
vectorAux[posAux++] = a[posLeft++];
} else {
vectorAux[posAux++] = a[posRight++];
}
}
while (posLeft <= endLeft) {
vectorAux[posAux++] = a[posLeft++];
}
while (posRight <= posEnd) {
vectorAux[posAux++] = a[posRight++];
}
for (int i = 0; i < numElemen; i++, posEnd--) {
a[posEnd] = vectorAux[posEnd];
}
}
//this is the method i've added to calculate the size
private static int calculateMid(int left, int right){
int mid = 0;
int tot = right-left+1;
int firstHalf = (int) (tot * coeff);
mid = left + firstHalf;
System.out.println(left+", "+mid +", "+firstHalf+", "+right + ", "+tot);
return mid-1;
}
public static void main(String[] args) {
int vector2[] = {10, 3, 15, 2, 1, 4, 9, 0};
System.out.println("Array not ordered: " + Arrays.toString(vector2) + "\n");
mergeSort(vector2);
System.out.println("Array ordered: " + Arrays.toString(vector2));
}}
Here is a hint: 这是一个提示:
Think about what calculateMid()
returns for a two-element array, and what happens in mergeSort()
after that. 考虑一下对于两个元素的数组, calculateMid()
返回什么,然后在mergeSort()
发生什么。
Once you figure out what happens there, it will also become clear why the code works for coeff >= 0.5
. 一旦弄清楚那里发生了什么,就可以清楚为什么代码对于coeff >= 0.5
起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.