Search code examples
javainfinite-loopmergesort

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++;
                }
            }
        }
    }
}

Solution

  • 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?