Search code examples
javamergesorthelperjgrasp

I try to make the merge sort go from bigger to little but it keep going from little to big


Trying to get it from big to little I'm trying to use the Sort & Search Merge Sort:

import java.util.*;

class MergeSorter {
   public static void sort(int[] a) {  
      if (a.length <= 1) { return; }
      int[] first = new int[a.length / 2];
      int[] second = new int[a.length - first.length];
      for (int i = 0; i < first.length; i++) { 
         first[i] = a[i]; 
      }
      for (int i = 0; i < second.length; i++) { 
         second[i] = a[first.length + i]; 
      }
      sort(first);
      sort(second);
      merge(first, second, a);
   }

   private static void merge(int[] first, int[] second, int[] a) {  
      int iFirst = 0;
      int iSecond = 0;
      int j = 0;

      while (iFirst < first.length && iSecond < second.length) {  
         if (first[iFirst] < second[iSecond]) {  
            a[j] = first[iFirst];
            iFirst++;
         } else {  
            a[j] = second[iSecond];
            iSecond++;
         }
         j++;
      }
      while (iFirst < first.length) { 
         a[j] = first[iFirst]; 
         iFirst++; j++;
      }
      while (iSecond < second.length) { 
         a[j] = second[iSecond]; 
         iSecond++; j++;
      }
   }
}

public class MergeSortDemo888888 {
   public static void main(String[] args) {
      int [] myAry = { 3, 2, 6, 7 };
      System.out.println("myAry is " + Arrays.toString(myAry));
      MergeSorter.sort(myAry);
      System.out.println("myAry is sorted descendingly using selection sort: "+Arrays.toString(myAry));
   }
}

Solution

  • In the first if in the merge function just change this (first[iFirst] < second[iSecond]) into this (first[iFirst] > second[iSecond]).