Skip to content

Instantly share code, notes, and snippets.

@myrtleTree33
Created December 30, 2019 14:15
Show Gist options
  • Save myrtleTree33/7b23aedf3f1424173b5b5685f623f33e to your computer and use it in GitHub Desktop.
Save myrtleTree33/7b23aedf3f1424173b5b5685f623f33e to your computer and use it in GitHub Desktop.
Algorithms / Arrays / Insertion Sort
package org.joeltong.test;
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] arr = new int[]{5,3,89,4,4,45,22,44,5,3};
insertionSort(arr);
System.out.println(Arrays.toString(arr));
}
static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = i;
while(j > 0 && arr[j-1] > arr[j]) {
swap(arr, j-1, j);
j--;
}
}
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment