0

Here is my Java code which is giving exception which I am able to figure it out. can anyone help me where am i being wrong? I am commenting the lines where Exception is being shown.

static void mergesort(int[] array,int low,int high){
    if(low<high){
        int mid = (low+high)/2;
        mergesort(array,low,mid);    //1
        mergesort(array,mid+1,high); //2
        merge(array,low,mid,high);   //3
    }
}
static void merge(int[] array,int low,int mid,int high){
    int[] array1 = new int[mid-low+2];
    int[] array2 = new int[high-mid+1];
    for(int i=0;i<array1.length-1;i++){
        array1[i] = array[i];
    }
    array1[array1.length-1] =  2147483640;
    for(int i=0;i<array2.length-1;i++){
        array2[i] = array[mid+i+1];
    }
    array2[array2.length-1] =  2147483640;
    for(int i=0,m=0,n=0;i<high;i++){
        if(array1[m]<array2[n]){    //4
            array[i] = array1[m];
            m++;
        }
        else{
            array[i] = array2[n];
            n++;
        }
    }
}

If it required, here is the driver program. Comment shows exception line in driver program but I think it is because of exceptions in functions.

    import java.util.Scanner;
public class Mergesort {
    public static void main(String[] str){
        Scanner in = new Scanner(System.in);
        int N = in.nextInt(), array[] = new int[N];
        System.out.println("Enter elements in the array");
        for(int i=0;i<N;i++){
            array[i] = in.nextInt();
        }
        in.close();
        mergesort(array,0,N-1);   //5
        System.out.println("Sorted array is:");
        for(int i=0;i<N;i++){
            System.out.println(array[i]);
        }
    }
Mr. Sigma.
  • 405
  • 1
  • 4
  • 15

0 Answers0