Java implementation of the Selection Sort Algorithm.
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 |
package com.example; public class SelectionSort { public static void main(String[] args) { int[] toSort = { 2, 9, 3, 6, 1, 0, 4, 5, 8, 7 }; System.out.println(); System.out.print("Given Array: "); for (int i = 0; i < toSort.length; i++) { System.out.print(toSort[i] + " "); } // main loop int temp; int min; int pos; for (int i = 0; i < toSort.length; i++) { min = toSort[i]; pos = i; for (int j = i + 1; j < toSort.length; j++) { if (toSort[j] < min) { pos = j; min = toSort[j]; } } temp = toSort[i]; toSort[i] = min; toSort[pos] = temp; System.out.print("\nStep " + (i + 1) + ": "); for (int k = 0; k < toSort.length; k++) { System.out.print(toSort[k] + " "); } } System.out.print("\nSorted Array: "); for (int i = 0; i < toSort.length; i++) { System.out.print(toSort[i] + " "); } } } |
output: