Skip to content

Instantly share code, notes, and snippets.

@veganaize
Last active February 20, 2024 01:28
Show Gist options
  • Save veganaize/21496c6b641c76d21fe172199813f8dd to your computer and use it in GitHub Desktop.
Save veganaize/21496c6b641c76d21fe172199813f8dd to your computer and use it in GitHub Desktop.
import java.util.concurrent.TimeUnit;
class InsertionSort {
public static void
main(String[] args) {
int[] unsortedArray = { 45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 6, 8 };
int[] sortedArray = sort(unsortedArray);
displayArray(sortedArray, -1);
}
static int[]
sort(int[] array) {
for (int i=1; i < array.length; ++i) { // For the length of the array
for (int j=i; j > 0; --j) { // Make a copy of the index
displayArray(array, j); // Display array with brackets
if (array[j] < array[j-1]) { // Less than value before it?
int smaller = array[j]; // Save smaller value to temp
array[j] = array[j-1]; // Move bigger value to right
array[j-1] = smaller; // Move smaller value to left
displayArray(array, j); // Display array with brackets
}
}
}
return array;
}
static void
displayArray(int[] array, int index) {
String resultString = "";
for (int i=0; i < array.length; ++i) {
if (i == index-1) resultString += "[";
resultString += array[i];
if (i == index) resultString += "]";
resultString += ", ";
}
System.out.print(resultString +"\b\b ");
System.out.flush();
try { TimeUnit.SECONDS.sleep(1L); } catch (Exception e) { }
for (int i=0; i < resultString.length(); ++i) System.out.print("\b");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment