Page 344 - ComputerScience_Class_11
P. 344
27 ar[min_idx] = ar[i];
28 ar[i] = temp;
29 }
30 for(i=0; i<=n-1; i++)
31 {
32 System.out.print(ar[i]+ " ");
33 }
34 }
35 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
Enter the number of elements: 5
Enter a number: 23
Enter a number: 32
Enter a number: 10
Enter a number: 4
Enter a number: 9
4 9 10 23 32
Insertion Sort
In this process, the second element is checked with the first element and if the element is found to be smaller than the
previous one, in the case of ascending sort, the first element is shifted by one index to the right and the second element
is placed in the front. Similarly, the third element is checked with the previous elements and as long as the condition is
satisfied the numbers are shifted, then the element in the third position is placed. This procedure continues until the
last iteration is executed. Insertion sort is the best among bubble sort and selection sort, as it performs well on small
or partially sorted data.
Let us take the following example,
The array is to be sorted in ascending order:
Index 0 1 2 3 4
Ar 10 5 14 7 21
Step 1: The second element is compared with the first element.
Index 0 1 2 3 4
Ar 10 5 14 7 21
Since, ar[1] < ar[0], i.e., 5 < 10 is true, shift the element.
342 Touchpad Computer Science (Ver. 3.0)-XI

