Write a program to implement an insertion sort Submit a scre

Write a program to implement an insertion sort.
Submit a screenshot of your Java source codes and IDE/Comment line results in PDF file.

Solution

public class SortingExample{

public static void main(String[] args) {
int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };//Random numbers to do the sorting
insertionSort(input); // This will call the method which has sorting logic
}

public static void insertionSort(int sortingArray[]) {
int a = sortingArray.length; //Store the length of array to be sorted in a variable a
for (int b = 1; b < a; b++) { //Iterate over array length
int key = sortingArray[b]; //Store the element starting from index 0 in an array
int i = b-1;
while ( (i > -1) && ( sortingArray [i] > key ) ) { //Compare the elements in array and check which one is greater
sortingArray [i+1] = sortingArray [i]; // replace the position of greater element to next position in array
i--;
}
sortingArray[i+1] = key;
printNumbers(sortingArray); //Invoke method to display on console
}
}
  
private static void printNumbers(int[] numbers) {

for (int i = 0; i < numbers.length; i++) { //Iterate over sorted array
System.out.print(numbers[i] + \", \"); //Display each element starting from index 0
}
System.out.println(\"\ \");
}

}

Console Output :-

2, 4, 9, 6, 23, 12, 34, 0, 1,

2, 4, 6, 9, 23, 12, 34, 0, 1,

2, 4, 6, 9, 23, 12, 34, 0, 1,

2, 4, 6, 9, 12, 23, 34, 0, 1,

2, 4, 6, 9, 12, 23, 34, 0, 1,

0, 2, 4, 6, 9, 12, 23, 34, 1,

0, 1, 2, 4, 6, 9, 12, 23, 34,

Write a program to implement an insertion sort. Submit a screenshot of your Java source codes and IDE/Comment line results in PDF file.Solutionpublic class Sort

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site