Skip to content

Instantly share code, notes, and snippets.

@yaboong
Created February 18, 2018 20:07
Show Gist options
  • Save yaboong/4d7feb990ee9cdcb1171f9de503c3a05 to your computer and use it in GitHub Desktop.
Save yaboong/4d7feb990ee9cdcb1171f9de503c3a05 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
/**
* Created by yaboong on 2018. 1. 15..
*/
public class InsertionSort {
public static void insertionSort(Comparable[] arr){
int N = arr.length;
for(int i = 0; i < N; i++){
for(int j = i; j > 0; j--){
if(less(arr[j], arr[j-1])) exch(arr, j, j-1);
else break;
}
}
System.out.println(Arrays.toString(arr));
}
private static boolean less(Comparable v, Comparable w){
return v.compareTo(w) < 0;
}
private static void exch(Comparable[] a, int i, int j){
Comparable swap = a[i];
a[i] = a[j];
a[j] = swap;
}
public static void main(String[] args) {
insertionSort(new String[]{"G", "F", "E", "D", "C", "B", "A"});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment