1

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));
   }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Try to dry run the code on the array you have chosen as example and see why it is sorting from little to big. Have a closer look at the `merge` function. Some reference to help: https://www.geeksforgeeks.org/merge-sort/ – Nikhil Sahu Apr 26 '20 at 08:43

1 Answers1

1

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

Alberto Ursino
  • 366
  • 3
  • 18