Skip to content

Instantly share code, notes, and snippets.

@ellbur
Created November 9, 2011 05:12
Show Gist options
  • Select an option

  • Save ellbur/1350468 to your computer and use it in GitHub Desktop.

Select an option

Save ellbur/1350468 to your computer and use it in GitHub Desktop.
Insertion Sorting
public class Sorting {
public static void main(String[] args) {
int[] array = { 8, 7, 6, 5, 4, 3, 2, 1 };
for (int i=1; i<array.length; i++) {
int j = i;
int a = array[i];
/**/ // Printing out the current state of things
/**/ for (int x=0; x<array.length; x++) {
/**/ if (x == i) {
/**/ System.out.print("[" + array[x] + "]" + " ");
/**/ }
/**/ else {
/**/ System.out.print(" " + array[x] + " " + " ");
/**/ }
/**/ }
/**/ System.out.println();
while (j > 0 && array[j-1] > a) {
/**/ // Printing out the current state of things
/**/ for (int x=0; x<array.length; x++) {
/**/ if (x == i) {
/**/ System.out.print("[" + array[x] + "]" + " ");
/**/ }
/**/ else if (x == j) {
/**/ System.out.print("(" + array[x] + ")" + " ");
/**/ }
/**/ else {
/**/ System.out.print(" " + array[x] + " " + " ");
/**/ }
/**/ }
/**/ System.out.println();
array[j] = array[j-1];
j--;
}
array[j] = a;
}
System.out.println(java.util.Arrays.toString(array));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment