SelectionSort.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public class SelectionSort<T extends Comparable<T>> { public void sort(T[] arr){ // i is the index before which the array is // already sorted. for (int i = 0; i < arr.length - 1; i++) { int minIndex = i; // Loop to find lowest value in remaining array space. for (int j = i + 1; j < arr.length; j ++) { if (arr[j].compareTo(arr[minIndex]) < 0) minIndex = j; } T smallest = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = smallest; } } public static void main(String[] args){ SelectionSort<Integer> ss = new SelectionSort<>(); Integer[] arr = {35, 65, 30, 60, 20}; ss.sort(arr); for (Integer i : arr) System.out.print(i + " "); System.out.println(); SelectionSort<String> ss2 = new SelectionSort<>(); String[] arr2 = {"The", "Quick", "Brown", "Fox"}; ss2.sort(arr2); for (String i : arr2) System.out.print(i + " "); System.out.println(); } } |