Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created September 11, 2016 11:58
Show Gist options
  • Select an option

  • Save nichtemna/4239f6dd2d8eacbd60c1d85009e6a98e to your computer and use it in GitHub Desktop.

Select an option

Save nichtemna/4239f6dd2d8eacbd60c1d85009e6a98e to your computer and use it in GitHub Desktop.
Insertion sort
/**
* Insertion sort O(n2):
- Take i-th element and find it’s place in the part of array that goes before it(this part already sorted)
- Slide all elements in sorted part of array to the right for 1 position and insert the element
- Precede! All elements to left of i-th element a sorted already
*/
public class InsertionSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
array = getArraySorted(array);
for (int i : array) {
System.out.print(i + " ");
}
}
private static int[] getArraySorted(int[] array) {
int value;
for (int i = 0; i < array.length; i++) {
value = array[i];
int pos = i;
for (int j = i - 1; j >= 0; j--) {
if (value < array[j]) {
array = slide(array, j);
pos = j;
}
}
array[pos] = value;
}
return array;
}
private static int[] slide(int[] array, int j) {
array[j + 1] = array[j];
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment