write a program that given a list of 20 integers sorts them
write a program that given a list of 20 integers, sorts them according to insert sort. java
Solution
public class InsertionSort {
/**
* method to sort the array elements using insertion sorts *
*
* @param array
* @return
*/
public static int[] insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j - 1;
while ((i > -1) && (array[i] > key)) {
array[i + 1] = array[i];
i--;
}
array[i + 1] = key;
}
return array;
}
/**
* method to print the array elements
*
* @param input
*/
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + \", \");
}
System.out.println(\"\ \");
}
/**
* @param args
*/
public static void main(String[] args) {
int[] input = { 3, 26, 67, 35, 9, -6, 43, 82, 10, 54, 14, 22, 21, 32,
121, 231, 12, 98, 77, 65 };
System.out.println(\"Before Sorting\");
printNumbers(input);
input = insertionSort(input);
System.out.println(\"Before Sorting\");
printNumbers(input);
}
}
OUTPUT:
Before Sorting
3, 26, 67, 35, 9, -6, 43, 82, 10, 54, 14, 22, 21, 32, 121, 231, 12, 98, 77, 65,
Before Sorting
-6, 3, 9, 10, 12, 14, 21, 22, 26, 32, 35, 43, 54, 65, 67, 77, 82, 98, 121, 231,

