Page 306 - Cs_withBlue_J_C11_Flipbook
P. 306
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
Element ar[1] and ar[2] are shifted to the next position and ar[3] is placed in the 1 index,
st
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 program in Java to input 10 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()
5 {
6 Scanner sc= new Scanner(System.in);
7 String ar[ ]=new String[5];
8 int i, j, pos=-1;
9 String n;
10 for(i=0; i<5; i++)
11 {
12 System.out.print ("Enter a name: ");
13 ar[i]=sc.next ();
304304 Touchpad Computer Science-XI

