class InsertionSort {
private static int[] array;
private void sort() {
for(int i = 1; i < array.length; i++) {
for(int j = i; j > 0 && less(j, j-1); j--) {
swap(j, j-1);
}
}
}
private void swap(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private boolean less(int i, int j) {
return array[i] < array[j];
}
private void display() {
for(int key : array) {
System.out.print(key + " ");
}
}
public static void main (String[] args) {
InsertionSort obj = new InsertionSort();
array = new int[] {11,13,7,12,16,9,24,5,10,3};
System.out.println("Unsorted array : ");
obj.display();
obj.sort();
System.out.println("\nSorted array : ");
obj.display();
}
}
Output
Unsorted array :
11 13 7 12 16 9 24 5 10 3
Sorted array :
3 5 7 9 10 11 12 13 16 24
Comments
Post a Comment