// SelectionSort.java // // CS 101 Class Example import java.util.*; // for Random number generator public class SelectionSort { // --------- Main program--------------------------------------------- public static void main(String[] args) { int n = 10; // default array size if (args.length > 0) { // if provided, n = Integer.parseInt(args[0]); // get array size from command line } int[] a = new int[n]; initArr(a); // initialize array with random numbers System.out.println(); System.out.print("Initial array: "); printArr(a); selectionSort(a); System.out.print("Sorted array: "); printArr(a); } // --------- Selection Sort ------------------------------------------ public static int minIndexBetween(int[] a, int lo, int hi) { // Return the index of the minimum integer in a[lo..hi] int minValue = a[lo]; int minIndex = lo; for (int i = lo+1; i <= hi; i++) { if (a[i] < minValue) { minValue = a[i]; minIndex = i; } } return minIndex; } public static void selectionSort(int[] a) { // Selection sort - iterative version for (int i = 0; i < a.length-1; i++) { int j = minIndexBetween(a, i, a.length-1); if (i != j) { swap(a, i, j); } } } public static void selectionSortRec(int[] a, int lo, int hi) { // Selection sort - recursive version if (lo < hi) { int j = minIndexBetween(a, lo, hi); swap(a, lo, j); selectionSortRec(a, lo+1, hi); } } // --------- Helper Methods ------------------------------------------ public static void swap(int[] a, int i, int j) { // Swap a[i] and a[j] int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } public static void initArr(int[] a) { // initialize array a with random numbers between 0 and 99 Random rand = new Random(); for (int i = 0; i < a.length; i++) { a[i] = Math.abs(rand.nextInt()) % 100; } } public static void printArr(int[] a) { // print array a for (int i=0; i < a.length; i++) { System.out.print(a[i] + " "); // print all elements on same line } System.out.println(); // print newline } }