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

Sorting and Searching Given the following code, implement a selectionSort method

ID: 3600747 • Letter: S

Question

Sorting and Searching

Given the following code, implement a selectionSort method below:

import java.util.List;
import java.lang.Comparable;
public class Sorter {

    public static <T extends Comparable<T> > void bubbleSort(List<T> theList) {
        int lastToConsider = theList.size();
        while (lastToConsider > 1) {
            for (int j=0; j<lastToConsider-1; j++) {
                if (theList.get(j).compareTo(theList.get(j+1)) > 0 ) {
                    swap(theList,j,j+1);
                }
            }
            lastToConsider--;
        }
    }

    private static <T extends Comparable<T> > void swap(List<T> theList, int i1, int i2) {

        T temp = theList.get(i1);
        theList.set(i1,theList.get(i2));
        theList.set(i2,temp);
    }

   public static <T extends Comparable<T> > void selectionSort(List<T> theList) {

        // stubbed

    }

Explanation / Answer

import java.util.ArrayList;
import java.util.List;
import java.lang.Comparable;

public class Sorter {

   public static <T extends Comparable<T>> void bubbleSort(List<T> theList) {
       int lastToConsider = theList.size();
       while (lastToConsider > 1) {
           for (int j = 0; j < lastToConsider - 1; j++) {
               if (theList.get(j).compareTo(theList.get(j + 1)) > 0) {
                   swap(theList, j, j + 1);
               }
           }
           lastToConsider--;
       }
   }

   private static <T extends Comparable<T>> void swap(List<T> theList, int i1, int i2) {

       T temp = theList.get(i1);
       theList.set(i1, theList.get(i2));
       theList.set(i2, temp);
   }

   public static <T extends Comparable<T>> void selectionSort(List<T> theList) {

       for (int index = 0; index < theList.size() - 1; index++) {
           int min = index;
           for (int scan = index + 1; scan < theList.size(); scan++)
               if (theList.get(scan).compareTo(theList.get(min)) < 0)
                   min = scan;//Find minimum
           // Swap the values
           swap(theList, min, index);
       }

   }
  
   public static void main(String args[]) {
       ArrayList<Integer> array = new ArrayList<Integer>();
       array.add(10);
       array.add(20);
       array.add(1);
       array.add(10);
       array.add(13);
       array.add(11);
       System.out.println(array);
       selectionSort(array);
       System.out.println(array);
      
   }
}

=======

[10, 20, 1, 10, 13, 11]
[1, 10, 10, 11, 13, 20]


===

Thanks

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