Page 346 - ComputerScience_Class_11
P. 346

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 ();
                14               }
                15               for(i=1; i<ar.length; i++)
                16               {
                17
                                     j=i;
                18                   n=ar[i];

                19                   while((j>0) && (ar[j-1].compareTo(n)>0)) // shifting to right
                20                   {
                21                       ar[j]=ar[j-1];
                22                       j--;

                23                   }
                24                   ar[j]=n;          // Placing in correct position
                25               }
                26                System.out.println("Names sorted in ascending order:");
                27               for(i=0; i<5; i++)
                28               {

                29                   System.out.print(ar[i] + " ");
                30               }
                31           }
                32       }

              The output of the preceding program is as follows:

                      BlueJ: Terminal Window - Java
                   Options

                  Enter a name:  Anya
                  Enter a name:  Samar
                  Enter a name:  Anuj

                  Enter a name:  Swara
                  Enter a name:  Deepansh
                  Names sorted in ascending order:
                  Anuj Anya Deepansh Samar Swara







                  344  Touchpad Computer Science (Ver. 3.0)-XI
   341   342   343   344   345   346   347   348   349   350   351