Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Selection Sort java Implements the selection sort algorithm. public class Select

ID: 3832120 • Letter: S

Question

Selection Sort java Implements the selection sort algorithm. public class Selection Sort Sort the array using selection sort algorithm. apre table contains Comparable objects. @post table is sorted. @param table The array to be sorted public static void sort CComparableCJ table) int n table. length for (int fill 0; fill n 1; fill Invariant tableCO fill 1] is sorted int posMin fill for (int next fill 1; next n next++) Invariant: tableCposMin] is the smallest item in table fill next 1]. if (table next].compareTo(table [posMin])

Explanation / Answer

PROGRAM CODE:

package sort;

public class SelectionSort<T> {

   public void print(Comparable<T>[] table)
   {
       for(int i=0; i<table.length; i++)
           System.out.print(table[i] + " ");
   System.out.println(" ");
   }
  
   public void sort(Comparable<T>[] table)
   {
       int n = table.length;
       int totalComparisons = 0;
       for(int fill = 0; fill<n-1; fill++)
       {
           int posMin = fill;
           System.out.println("Comparing index " + fill + " with other elements");
           for(int next = fill+1; next<n; next++)
           {
              
               if(table[next].compareTo((T) table[posMin]) < 0)
               {
                   posMin = next;
                   totalComparisons++;
               }
           }
           Comparable<T> temp = table[fill];
           table[fill] = table[posMin];
           table[posMin] = temp;
           print(table);
       }
       System.out.println("Total comparisons: " + totalComparisons);
   }
  
   public static void main(String[] args) {
       SelectionSort<String> sorter = new SelectionSort<>();
       sorter.sort(new String[]{"Lime", "Mango", "Orange", "Kiwi", "Grape","Apple"});

   }

}

OUTPUT:

Comparing index 0 with other elements
Apple Mango Orange Kiwi Grape Lime

Comparing index 1 with other elements
Apple Grape Orange Kiwi Mango Lime

Comparing index 2 with other elements
Apple Grape Kiwi Orange Mango Lime

Comparing index 3 with other elements
Apple Grape Kiwi Lime Mango Orange

Comparing index 4 with other elements
Apple Grape Kiwi Lime Mango Orange

Total comparisons: 8

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote