Created
February 18, 2018 20:07
-
-
Save yaboong/4d7feb990ee9cdcb1171f9de503c3a05 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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