Java examples for Data Structure:Sort
Implements a Insertion sort
class Insertion { public static void sort(Comparable[] a) { int N = a.length; for (int i = 0; i < N; i++) { for (int j = i; j > 0; j--) { if (less(a[j], a[j - 1])) exch(a, j, j - 1);// w w w. j a v a 2s . c o m else break; } } } 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) { Integer[] data = new Integer[] { 5, 1, 3, 7, 4, 8, 1, 38, 10, 9, 8, 44 }; sort(data); System.out.print("Array sorted by Insertion sort: "); for (Integer x : data) { System.out.printf("%s ", x); } } }