drjava

Make both sorting algorithms put the values in descending order. Then create drive class to test the two algorithms


I am extremely confused on how to reverse these sorting methods. Any help would be appreciated. I have looked up and tried researching but I could not find anything to do with this type of comparable list.

public class Sorting
{

   public static void selectionSort(Comparable[] list)
   {
      int min;
      Comparable temp;

      for (int index = 0; index < list.length-1; index++)
      {
         min = index;
         for (int scan = index+1; scan < list.length; scan++)
            if (list[scan].compareTo(list[min]) < 0)
               min = scan;

         temp = list[min];
         list[min] = list[index];
         list[index] = temp;
      }
   }

   public static void insertionSort(Comparable[] list)
   {
      for (int index = 1; index < list.length; index++)
      {
         Comparable key = list[index];
         int position = index;

         while (position > 0 && key.compareTo(list[position-1]) < 0)
         {
            list[position] = list[position-1];
            position--;
         }

         list[position] = key;
      }
   }
}

Solution

  • I think if you change: if (list[scan].compareTo(list[min]) < 0) to if (list[scan].compareTo(list[min]) > 0) it will sort in reverse order.

    Here is the api

    int compareTo(T o)

    Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.