Page 343 - ComputerScience_Class_11
P. 343

Index         0          1           2           3           4

                                       Ar         16          12          16         21          27
                        After the fourth step, the array has been sorted in ascending order.

                 We can clearly see that the selection sort technique performs a smaller number of swaps as compared to the bubble
                 sort technique. Thus, it performs faster and more efficiently than the bubble sort.


                   Program 11    Write a Java program to input 5 numbers in an array and sort the numbers in an ascending
                                 order. (Use Selection sort technique)
                   1       import java.util.*;
                   2       class Selection_sort

                   3       {

                   4           public static void main(String args[])
                   5           {
                   6               Scanner sc=new Scanner(System.in);

                   7               System.out.print("Enter the number of elements: ");
                   8               int n=sc.nextInt();

                   9               int ar[]=new int[n];
                   10              int i, j, temp;

                   11              for (i=0; i<n; i++)
                   12              {

                   13                  System.out.print("Enter a number: ");
                   14                  ar[i]=sc.nextInt();

                   15              }
                   16              for (i = 0; i < n-1; i++)

                   17              {
                   18                  int min_idx = i;

                   19                  for (j = i+1; j < n; j++)
                   20                  {

                   21                      if (ar[j] < ar[min_idx])
                   22                      {

                   23                          min_idx = j;
                   24                      }

                   25                  }
                   26                  temp = ar[min_idx];








                                                                                                           Arrays  341
   338   339   340   341   342   343   344   345   346   347   348