Add

Java Program for Selection Sorting

 


How Selection Sort algorithm works?

Selection sort algorithm works by dividing the original array in two subarrays: Sorted subarray and unsorted subarray, initially the sorted subarray is empty. This algorithm works by repeatedly finding the minimum element from the unsorted subarray and replacing it with the first element of the array, thus making that part of the array as sorted subarray. This happens repeatedly until the whole array is sorted.

Java Program to perform Selection Sort on Array.

In the following example, we have defined a method selectionSort() that implements the selection sort algorithm. It finds the minimum element from the array and swaps it with the first element of the array.

We have created another method printArr() to display the elements of the array. We have called this method before and after sorting to display the array elements before and after selection sorting.

class JavaExample

{

    void selectionSort(int arr[])

    {

        int len = arr.length;

        for (int i = 0; i < len-1; i++)

        {

            // Finding the minimum element in the unsorted part of array

            int min = i;

            for (int j = i+1; j < len; j++)

                if (arr[j] < arr[min])

                    min = j;

            /* Swapping the found minimum element with the first

             * element of the sorted subarray using temp variable

             */

            int temp = arr[min];

            arr[min] = arr[i];

            arr[i] = temp;

        }

    }

    // Displays the array elements

    void printArr(int arr[])

    {

        for (int i=0; i<arr.length; i++)

            System.out.print(arr[i]+" ");

        System.out.println();

    }

    public static void main(String args[])

    {

        JavaExample obj = new JavaExample();

        int numarr[] = {101,5,18,11,80, 67};  

        System.out.print("Original array: ");

        obj.printArr(numarr);

        //calling method for selection sorting

        obj.selectionSort(numarr);      

        System.out.print("Sorted array: ");

        obj.printArr(numarr);

    }

}

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.