Below is a complete working program which performs a Selection Sort. Run the code in BlueJ and make sure you understand how it works.
/** * The selection sort algorithm */ public class SelectionSort { public static void sort(int numbers[]) { int i, j; int min, temp; for (i = 0; i < numbers.length-1; i++) { min = i; // set first item to minimun for (j = i+1; j < numbers.length; j++) { if (numbers[j] < numbers[min]) min = j; // new minimum found } // swap values temp = numbers[i]; numbers[i] = numbers[min]; numbers[min] = temp; } } }
public class SortTester { public static void main(String args[]) { int[] numArray = {10,6,12,7,1,2,20,4,9,8,0,3,22,5}; // Before the sort for (int x : numArray) System.out.print(x + " "); System.out.println(""); SelectionSort.sort(numArray); // After the sort for (int x : numArray) System.out.print(x + " "); System.out.println(""); } }