Selection Sort




Program In Java To Sort The Given Array Using Selection Sort Algorithm.

The Following Program Reads The Elements Of An Array From User And Then It Sorts The Array In Ascending Order Using Selection Sort Algorithm And Displays The Sorted Array

import java.io.*;
class Selection {
    void sSort(int[] a) //Selection Sort Algorithm
    {
        int i, j, k, cmp = 0;
        for (i = 0; i < a.length - 1; i++) //ith element is selected element
            for (j = i + 1; j < a.length; j++, cmp++) //Compare ith element with all the
                //down elements starting from i+1
                if (a[i] > a[j]) {
                    k = a[i];
                    a[i] = a[j];
                    a[j] = k;
                }
        System.out.println("\n\nNo.Of Comparisons For " + a.length + " Element is " + cmp);
    }
    public static void main(String[] arg) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter Total Number Of Elements In An Array::");
        int t = Integer.parseInt(br.readLine());
        int[] arr = new int[t];
        for (int i = 0; i < t; i++) {
            System.out.print("\nEnter Element::");
            int e = Integer.parseInt(br.readLine());
            arr[i] = e;
        }
        //int []arr={5,4,15,16,17,3,2,1};
        Selection s = new Selection();
        s.sSort(arr);
        System.out.println("\n\nAfter Sorting Array Is::");
        for (int i = 0; i < arr.length; i++) System.out.println(arr[i]);
    }
}


OUTPUT:


Enter Total Number Of Elements In An Array::8

Enter Element::5

Enter Element::4

Enter Element::15

Enter Element::16

Enter Element::17

Enter Element::3

Enter Element::2

Enter Element::1

After Sorting Array Is::
1
2
3
4
5
15
16
17
Previous Post Next Post