Additionally, your sort function should only sort, not print.
Here's the final result
private static void insertionSort(int[] toSort) {
for (int i = 1; i < toSort.length; i++) {
// set key to value at index i
int key = toSort[i];
// set j as i-1 to look for previous element
int j = i - 1;
while (j >= 0 && toSort[j] > key) {
toSort[j + 1] = toSort[j];
j--;
}
toSort[j + 1] = key;
}
}
Going further
Insertion sort is a nice sorting algorithm that works for much more than just ints; you can sort doubles, BigIntegers, or even user-defined objects. Why not generify the function? You could do the following:
private static <T extends Comparable<T>> void insertionSort(T[] toSort) {
for (int i = 1; i < toSort.length; i++) {
// set key to value at index i
T key = toSort[i];
// set j as i-1 to look for previous element
int j = i - 1;
while (j >= 0 && toSort[j].compareTo(key) > 0) {
toSort[j + 1] = toSort[j];
j--;
}
toSort[j + 1] = key;
}
}
private static <T> void insertionSort(T[] toSort, Comparator<T> compare) {
for (int i = 1; i < toSort.length; i++) {
// set key to value at index i
T key = toSort[i];
// set j as i-1 to look for previous element
int j = i - 1;
while (j >= 0 && compare.compare(toSort[j], key) > 0) {
toSort[j + 1] = toSort[j];
j--;
}
toSort[j + 1] = key;
}
}
This should allow you to sort arbitrarily typed arrays, except for the primitive types, unfortunately (although I did not compile the code).