Page 307 - Cs_withBlue_J_C11_Flipbook
P. 307

14              }
                   15              for(i=0; i<5; i++)

                   16              {
                   17                  System.out.print(ar[i] + " ");

                   18              }
                   19              for(i=1; i<ar.length; i++)

                   20              {
                   21                  j=i;
                   22                  n=ar[i];

                   23                  while((j>0) && (ar[j-1].compareTo(n)>0)) // shifting to right

                   24                  {
                   25                      ar[j]=ar[j-1];
                   26                      j--;

                   27                  }
                   28                  ar[j]=n;          // Placing in correct position

                   29              }
                   30              System.out.println();

                   31              for(i=0; i<5; i++)
                   32              {

                   33                  System.out.print(ar[i] + " ");
                   34              }

                   35          }
                   36      }

                 The output of the preceding program is as follows:
                 Enter a name: Anya
                 Enter a name: Samar
                 Enter a name: Anuj
                 Enter a name: Swara

                 Enter a name: Deepansh
                 Anya Samar Anuj Swara Deepansh
                 Anuj Anya Deepansh Samar Swara

                     11.5 INSERTION
                 An element can be added to an array even after its declaration. Insertion is the process of adding an element at any
                 desired position in the array. For the insertion of a new value into the array, we should have the value to be inserted as
                 well as the index of the position where the value has to be inserted.The last index of the array should be empty before
                 applying this technique.



                                                                                                                       305
                                                                                                              Arrays   305
   302   303   304   305   306   307   308   309   310   311   312