[英]Mergesort - Stackoverflow when splitting array not in a half
我有问题 我必须编辑标准mergesort算法,更改数组两半之间的比率。 标准mergesort在2中拆分数组。但是我必须用系数对其进行拆分。
例:
我有一个10个元素的数组,我必须以0.2的系数进行拆分。 这意味着第一次将数组划分为2个部分:一个包含2个元素,第二个包含8个元素。 由于是递归的,因此每次拆分数组时都会应用此比率。
问题:
如果系数> = 0.5,则没有概率。 如果比率<= 0.5,则每次尝试都会导致堆栈溢出。
任何帮助将不胜感激!
这里的课:
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));
}}
这是一个提示:
考虑一下对于两个元素的数组, calculateMid()
返回什么,然后在mergeSort()
发生什么。
一旦弄清楚那里发生了什么,就可以清楚为什么代码对于coeff >= 0.5
起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.