Tuesday, July 30, 2013

Merge Sort

This is a simple implementation of Merge Sort in java.
Though this is not the most efficient one, but still this can be considered as one version of implementation. I will post as and when I make improvements.


public class MergeSort {
    public static void main(String...args) {
        int a[]={3,2,5,1,3,2,7,8,6,4,0,7,9};
        System.out.println("len:"+a.length);
        MergeSort m = new MergeSort();
        int p = 0;
        int r = a.length;
        m.mergeSort(p,r-1,a);
        System.out.println("output:");
        for(int n=0; n< a.length;n++) {
            System.out.print(a[n]);
        }
    }
   
    public void mergeSort(int p, int r,int...a1) {
        if (p < r) {
            int q = (int) Math.floor((p+r)/2);
            mergeSort(p,q,a1);
            mergeSort(q+1,r,a1);
            merge(p,q,r,a1);
        }
    }
   
    public void merge(int p, int q, int r, int...a1) {
      int n1 = q-p+1;
      int n2= r-q;
         
      int[] a2= new int[n1];
      int[] a3= new int[n2];
     
      for(int i=0;i<n1;i++) {
          a2[i]=a1[p+i];
      }
     
      for(int i=0;i<n2;i++) {
          a3[i]= a1[q+i+1];
      }
     
      int k=0,l=0;
      int o;
      for(o=p;o<=r;o++) {
          if((k==n1) || (l==n2)){
              break;
          }
        if(a2[k] < a3[l]) {
          a1[o]=a2[k];
          k++;
        } else {
            a1[o] = a3[l];
            l++;
        }
      }
     
      if(k<n1){
          while(k<n1) {
              a1[o]=a2[k++];
              o++;
          }
      } else if(l<n2) {
          while(l<n2) {
              a1[o]=a3[l++];
              o++;
          }
      }
    }
}

No comments:

Post a Comment