Page 345 - ComputerScience_Class_11
P. 345
th
Element ar[0] is shifted to the next position and ar[1] is placed in the 0 index,
Index 0 1 2 3 4
Ar 5 10 14 7 21
Step 2: The second element is compared with the third element.
Index 0 1 2 3 4
Ar 5 10 14 7 21
Since, ar[2] < ar[1], i.e., 14 < 10 is false;
There is no shift of elements.
Index 0 1 2 3 4
Ar 5 10 14 7 21
Step 3: The third element is compared with the fourth element.
Index 0 1 2 3 4
Ar 5 10 14 7 21
Since, ar[3] < ar[2] , i.e. 7 < 14 is true
Index 0 1 2 3 4
Ar 5 10 14 7 21
Since, ar[3] < ar[1] , i.e. 7 < 10 is true
st
Element ar[1] and ar[2] are shifted to the next position and ar[3] is placed in the 1 index,
Index 0 1 2 3 4
Ar 5 7 10 14 21
Step 4: The fourth element is compared with the fifth element.
Index 0 1 2 3 4
Ar 5 7 10 14 21
Now, since 21 is the largest element in the array, so, there will be no shifting of elements.
And the array is sorted.
Program 12 Write a Java program to input 5 names in an array and sort the names in an ascending order.
(Use Insertion sort technique)
1 import java.util.*;
2 class insertion_sort_name
3 {
4 public static void main(String args[])
5 {
Arrays 343

