The insertion sort algorithm is given on the right. It is a sorting algorithm in which the elements are transferred one at a time to the right position. In other words, an insertion sort helps in building the final sorted list, one item at a time, with the movement of higher-ranked elements. |
|
args
.
|
|
// Java program for insertion sort public class InsertionSort { // Driver method public static void main( String args[ ] ) { Integer array[ ] = new Integer[ args.length ]; for ( int i = 0; i < args.length; i++ ) array[i] = Integer.parseInt( args[i] ); InsertionSort ob = new InsertionSort( ); ob.sort( array ); printArray( array ); } // Method to sort array using insertion sort void sort( Integer arr[ ] ) { int n = arr.length; for ( int i = 1; i < n; ++i ) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position. */ while ( j >= 0 && arr[j] > ) { arr[j+1] = arr[j]; j = j - 1; } arr[j+1] = ; } } // A utility method to print array of size n static void printArray( Integer arr[ ] ) { int n = arr.length; for ( int i = 0; i < n; ++i ) System.out.print( arr[i] + " " ); System.out.println( ); } } |
|
|
|