/** * Implements two sorting algorithms: selection sort and bubble sort * * @author alchambers * @version Fall 2015 */ public class Sorting { /** * Uses the selection sort algorithm to sort an array of integers * @param array the array to be sorted */ public static void selectionSort(int[] array){ // Each iteration of this outer for-loop puts one element into its proper place // Thus, after n iterations, every element is in its proper place // I.e., the array is sorted for(int i = 0; i < array.length; i++){ // Find the index of the smallest element in the // remaining unsorted portion of the array int minIndex = i; for(int j = i+1; j < array.length; j++){ if(array[j] < array[minIndex]){ minIndex = j; } } // Swap the ith element and the minimum element swap(array, i, minIndex); } } /** * Uses the Bubble sort algorithm to sort an array of integers * @param array the array to be sorted */ public static void bubbleSort(int[] array){ // Each iteration of this outer for-loop puts *at least* one element into its proper place // Thus, at most n iterations must be executed to sort the array // I.e., it's possible for the array to be sorted in fewer than n iterations for(int i = 0; i < array.length; i++){ boolean swapped = false; for(int j = 1; j < array.length; j++){ if(array[j-1] > array[j]){ swap(array, j-1, j); swapped = true; } } // If we went through the whole array and never swapped anything // then the array is sorted and we can exit early if(swapped == false){ return; } } } private static void swap(int[] array, int index1, int index2){ int temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; } }