/********************************************************************* * Author: Eric Heim * Date Created: 6/16/2011 * Course: CS0007 * Description: Shows the selection sort algorithm on an array *********************************************************************/ public class SelectionSort { public static void main(String[] args) { //Array to be sorted int[] sortArray = {33, 43, 6, 72, 21, 41, 62}; int startScan, //The spot in the array we start sorting minIndex, //The index of the minimum element for the current iteration minValue; //The value of the minimum element for the current iteration //Print the array before sorting System.out.println("Array before sorting: "); for(int i = 0; i < sortArray.length; i++) System.out.println(sortArray[i]); //Outer loop sorts one number per iterations for(startScan = 0; startScan < (sortArray.length-1); startScan++) { //Initialize the minimum index and minimum value to the element //this iteration starts at minIndex = startScan; minValue = sortArray[startScan]; //Loop through all elements starting at the starting point for(int i = startScan + 1; i < sortArray.length; i++) { //If the current element is smaller than our current minimum //set the minimum value and index accordingly if(sortArray[i] < minValue) { minValue = sortArray[i]; minIndex = i; } } //Swap the minimum element and the start of our current iter- //ation sortArray[minIndex] = sortArray[startScan]; sortArray[startScan] = minValue; } //Print the array after the sort System.out.println("\nArray after sorting: "); for(int i = 0; i < sortArray.length; i++) System.out.println(sortArray[i]); } }