Java implementation of the Insertion 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 |
package com.coddicted.sort; public class InsertionSort { public static void main(String args[]) { int[] toSort = { 2, 9, 3, 6, 1, 0, 4, 5, 8, 7 }; System.out.print("\nGiven Array:\t"); for (int i = 0; i < toSort.length; i++) { System.out.print(toSort[i] + " "); } int temp; // main loop for (int i = 0; i < toSort.length; i++) { for (int j = i; j > -1; j--) { if (j - 1 > -1 && toSort[j] < toSort[j - 1]) { temp = toSort[j - 1]; toSort[j - 1] = toSort[j]; toSort[j] = 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: