Problem with Merge Sort Alg Implementation

  • Context: Java 
  • Thread starter Thread starter zak100
  • Start date Start date
  • Tags Tags
    Sort
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
zak100
Messages
462
Reaction score
11
Hi,
I am trying to implement merge Sort Alg in Java. I am not getting any error but its not printing sorted list . can some body please guide me? My code is:
Java:
import javax.swing.*;

public class MergeAlg2{
   static int[ ] arr={2, 4, 5, 7, 1, 3, 6, 8}; 
 
   int [ ] L;
   int [ ] R;
   void merge(int [ ] arr, int p, int q, int r){
      int n1 = q- p +1;
      int n2 = r-q;
      L = new int[n1+1];
      R = new int[n2+1];
      int i=0;
      int j=0;
      for(  i=0;  i< n1; ++i)
         L[I] = arr[p +i -1];
      for(j=0; j<n2; ++j)
         R[j] = arr[q+j];
      L[n1] =100000;
      R[n2]= 100000;
      i=0;
      j=0;
      int k=0;
      for(k=p-1; k<r; ++k){
         if(L[ i ] <= R[j]){
            arr[k] = L[ i ];
           i++;
         }
         else{
            arr[k] = R[j];
            j++;
         }
      }
   }
   void merge_sort(int[ ] a, int left, int right){
      int i=0;
      String str="";
      if(left <right) {
         JOptionPane.showMessageDialog(null," Enters left = " + left  + "right= " + right );
         int center = (left + right)/2;
         merge_sort(a, left, center);
         merge_sort(a, center + 1, right);
         merge(a, left, center, right);
       }
       for(i=0; i<=7; ++i){
         str= str + a[ i ];
      } 
      JOptionPane.showMessageDialog(null, "Sorted List is" + str);
   }
   public static void main(String[ ] args){
      MergeAlg2 obj = new MergeAlg2();
      obj.merge_sort(arr, 1,8);
      int i=0;
   
      String str="";
      for(i=0; i<=7; ++i){
         str= str + arr[ i ];
      } 
      JOptionPane.showMessageDialog(null, str);
  }
}

My initial list is: {2, 4, 5, 7, 1, 3, 6, 8};

But after sorting i am getting: 2, 3, 4, 5, 6, 7, 1, 8

Zulfi.
 
Last edited by a moderator:
on Phys.org
Have you tried stepping through your code via a debugger or using print statements?

Look at where the sort makes a decision and decide if that's what it should do.
 
The first thing you need to do is decide what the p,q,r parameters mean and then follow that decision throughout your code.
Since your use is somewhat unintuitive, you may need to add comments such as
Java:
//first chunk:  a[p-1] to a[q-1]
//second chunk: a[q] to a[r]

You may want to change the arguments p,q,r so that the first call would become
Java:
mergesort(arr, 0, 8)
and the split would be
Java:
mergesort(a, left, center)
mergesort(a, center, right)