Search code examples
javaalgorithmsortingmergesort

MergeSort-My first DS algo in java


package allSortings;
import java.util.Scanner;
public class MergeSort {
public static int A[],B[];
void mergeArray(int A[],int first,int mid,int last){
    int i=first,j;
    j=mid;
    while(i<=mid && j<=last)
    {
        if(A[i]<A[j])
            B[first++]=A[i++];
        else B[first++]=A[j++];
    }

    while(i<=mid)
        B[first++]=A[i++];
    while(j<=last)
        B[first++]=A[j++];
}
void copyArray(int A[],int last,int B[])
{
    int i=0;
    while(i<last)
    {
        A[i]=B[i];i++;
    }
}
void splitArray(int A[],int first,int last)
{
    if(first<last)
    {
        int mid=first+last/2;
        System.out.println("first:"+first);
        splitArray(A,first,mid);
        splitArray(A,mid+1,last);
        //mergeArray(A,first,mid,last);
        //copyArray(A,last,B);
    }
}

public static void main(String args[])
{

    int n;
    A=new int[100];
    B=new int[100];
    System.out.println("Enter the no. of elements in the Array:"+"\n");
    Scanner input;
    input=new Scanner(System.in);
    n=input.nextInt();
    MergeSort m1=new MergeSort();
    for(int i=0;i<n;i++)
        A[i]=input.nextInt();
        System.out.println("\nThe Original array is:");
        for(int i=0;i<n;i++)
            System.out.format("%d"+" ",A[i]);
        m1.splitArray(A,0,n-1);
        System.out.println("\nThe Sorted array is:");
        for(int i=0;i<n;i++)
            System.out.format("%d"+" ",A[i]);
}

}

I keep getting at allSortings.MergeSort.splitArray(MergeSort.java:34).Guys any clue (I am new to Java, so I dont know to use a debugger)? The value of "first" variable always gets 2 and then does not change.


Solution

  • You're only dividing one summand by 2, but you should divide the sum by 2 instead. Replace

    int mid=first+last/2;
    

    with

    int mid=(first+last)/2;