簡體   English   中英

Mergesort-將數組拆分為一半時的Stackoverflow

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM