简体   繁体   中英

Merge Sort algorithm Infinite loop

I am trying to create a merge sort algorithm, but when I go to sort the broken down arrays, I enter an infinite loop, the main problem is happening in my merge method below. Thanks in advance for the help.

public static void mergeSort(double[] arr)
{
    int count = n;
    long startTime = System.currentTimeMillis();
    int mid = arr.length;
    if(arr.length > 1)
    {
        mid = arr.length/2;
    }
    else
    {
        return;
    }

    double[] a = new double[mid];
    double[] b = new double[arr.length-mid];

    for(int i = 0; i < a.length; i++)
    {
        a[i] = arr[i];
        System.out.println("A = " + a[i]);
        count++;
    }
    for(int i = 0; i < b.length; i++)
    {
        b[i] = arr[i+mid];
        System.out.println("B = " + b[i]);
        count++;
    }

    mergeSort(a);
    mergeSort(b);
    merge(arr, a, b);
}

public static void merge(double[] arr, double[] a, double [] b)
{
    int elem = a.length + b.length;
    int i,j,k;
    i = j = k = 0;
    while(i < elem )
    {
        if((j < a.length) && (k < b.length))
        {
            if(a[j] < b[k])
            {
                arr[i] = a[k];
                i++;
                j++;
            }
            else
            {
                arr[i] = b[k];
                i++;
                k++;
            }
        }
        else
        {
            if(j >= a.length)
            {
                while(k < b.length)
                {
                    arr[i] = b[k];
                    i++;
                    k++;
                }
            }
            if(k >= b.length)
            {
                while(j >= a.length)
                {
                    arr[i] = a[j];
                    j++;
                    i++;
                }
            }
        }
    }
}
while(j >= a.length)
{
    arr[i] = a[j];
    j++;
    i++;
}

I wonder what happens here....

while j>=a.length, do something, and make j bigger... when do you expect this to end?

If j is greater than a.length to begin with (which probably is), then there's your infinite loop.

while(j >= a.length)
            {
                arr[i] = a[j];
                j++;
                i++;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM