Write a Java program implementing the insertion sort on a ra
Write a Java program implementing the insertion sort on a randomly generated list of integers at least ten elements long. The sort should be able to handle both even and odd sized lists. Display the list pre- mid- and post- sort. Run the program several times on lists of varying lengths
Solution
public class sort {
public static void main(String[] args) {
int[] input = { 3 , 7 , 2 , 6 ,9 , 4 , 22 , 15 , 16 , 65};
insertionSort(input);
}
private static void display(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + \", \");
}
System.out.println(\"\ \");
}
public static void insertionSort(int array[]) {
System.out.println(\"Before sort : \");
int n = array.length;
for(int k=0;k<n;k++)
{
System.out.print(array[k]+\" \");
}
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;
}
System.out.println(\"\ After sort : \");
display(array);
}
}
Output :
Before sort :
3 7 2 6 9 4 22 15 16 65
After sort :
2, 3, 4, 6, 7, 9, 15, 16, 22, 65,
