-1

I have wriiten a code for mergesort(recursive) in java. I tried debugging it in IntelliJ but it didn't do anything

public class Main {

    public static void main(String[] args) {
        int[] ar = {20, 35, -15, 7, 55, 1, -22};
        mergeSort(ar);
        System.out.println(Arrays.toString(ar));
    }

    private static void mergeSort(int[] arra) {
        int l=arra.length;
        int mid = l/2;
        int[] left= Arrays.copyOfRange(arra,0,mid);
        int[] right= Arrays.copyOfRange(arra,mid,l);
        mergeSort(left);
        mergeSort(right);
        merge(left,right,arra);

    }

    public static void merge(int[] ll,int[] rr,int[] array) {
        int nl = ll.length;
        int nr = rr.length;
        int l=0;int r=0;int a=0;
        while(l<=nl && r<= nr) {
            array[a++]=ll[l]<=rr[r] ? ll[l++] : rr[r++];
        }

        if (l<nl) {
            while (l <= nl)
                array[a++] = ll[l++];
        }

        if (r<nr) {
            while (r<=nr)
                array[a++] = rr[r++];
        }
    }

Problem seems to be in line 21 i.e. "mergesort(left);"

Also there was no red underlines on the code as well, still nothing, still it resulted into nothing.

deHaar
  • 17,687
  • 10
  • 38
  • 51

1 Answers1

0

There is an infinite loop in mergeSort(). Put an if case around the code inside the function like so :

private static void mergeSort(int[] arra) {
    if (arra.length > 1) {
        int l = arra.length;
        int mid = l / 2;
        int[] left = Arrays.copyOfRange(arra, 0, mid);
        int[] right = Arrays.copyOfRange(arra, mid, l);
        mergeSort(left);
        mergeSort(right);
        merge(left, right, arra);
    }
}

Also in the function merge() replace <= with < in while and if conditions like so :

while (l < nl && r < nr) {
    array[a++] = ll[l] <= rr[r] ? ll[l++] : rr[r++];
}

if (l < nl) {
    while (l < nl)
        array[a++] = ll[l++];
}

if (r < nr) {
    while (r < nr)
        array[a++] = rr[r++];
}
raviiii1
  • 936
  • 8
  • 24