Thursday 3 March 2016

Selection Sort: Java Code

Selection sort is noted for its simplicity, and it has advantages when auxiliary memory is limited.

The algorithm divides the input list into two parts:

1. The sublist of items already sorted, which is built up from left to right at the front (left) of the list, and

2. The sublist of items remaining to be sorted that occupy the rest of the list.

Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

Example:
54 35 22 32 21 // this is the initial, starting state of the array

21 35 22 32 54 // sorted sublist = {21}

21 22 35 32 54 // sorted sublist = {21, 22}

21 22 32 35 54 // sorted sublist = {21, 22, 32}

21 22 32 35 54 // sorted sublist = {21, 22, 32, 35}

21 22 32 35 54 // sorted sublist = {21, 22, 32, 35, 54}

Complexity:
Best Case           :    O(n^2)
Average Case  :    O(n^2)
Worst Case      :    O(n^2)

import java.util.Scanner;
public class SelectionSort {
     public static int[] sort(int[] arr) {

           // outer loop to maintain the index of sorted array.
           for (int i = 0; i < arr.length - 1; i++) {
                int index = i;

                // inner loop is searching in unsorted list.
                for (int j = i + 1; j < arr.length; j++) {

                     // check for smallest number’s index.
                     if (arr[j] < arr[index]) {
                           index = j;
                     }
                }

                // swap with left most unsorted index.
                int smallerNumber = arr[index];
                arr[index] = arr[i];
                arr[i] = smallerNumber;
           }
           return arr;
     }

     public static void main(String...args) {
           Scanner scan = new Scanner(System.in);
           System.out.println("Enter the no. of elements:");
           int size = scan.nextInt();
           int[] array = new int[size];
          
           for(int i = 0;i<size;i++) {
                array[i] = scan.nextInt();
           }
           int[] sortedArray = sort(array);
           for(int e : sortedArray){
                System.out.print(e+" ");
           }
     }
}

Output:
Enter the no. of elements:
5
54 35 22 32 21
21 22 32 35 54 

References:

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...