Java Selection Sort Algorithm Tutorial

Introduction

Selection Sort algorithm is another simpler sorting algorithm in the family of O(N^2) sorting algorithms. It is better than bubble sort with respect to runtime complexity. It operates to construct a sorted sequence by selecting one element at a time from raw data set and add the element to the sorted data set in order. In each iteration of its outer loop the selection sort algorithm selects next candidate element from the unsorted or raw dataset and adds it to the sorted data set at right place until all the raw data elements are selected. The result is the sorted data according to the defined order ascending, descending or any custom order based on the data set and implementation criteria. This is an in-place stable sorting algorithm. Selection sort algorithm is easier to implement. It is inefficient for large data set being very slow and has the worst-case complexity of O(N^2).

How it Works

  • It maintains two subarrays or lists: Sorted and Unsorted.
  • To achieve sorting order as it iterates the unsorted list and finds or selects the minimum element from the unsorted sub-array or list and inserts it into a sorted subarray or list.

Selection Sort Complexity Analysis

FillArray.java

import java.util.Random;
/**
 * Class will fill a given array of size N, in a range
 * of integers Min-Max
 *
 * @author CodingHelpLine
 * Web: https://codinghelpline.org
 */
public class FillArray {
   
    // Delcare Random object at class level
    private static Random random = new Random();
   
    /**
     * Fill an array of given size with given range of integers.
     *
     * @param array
     * @param min
     * @param max
     */
    public void fillArray(int array [], int min, int max) {
       
        // fill the array
        // iterate using for loop size time
        for(int counter = 0; counter < array.length; counter++) {
            array[counter] = generateRandom(min, max);
        }
    }
   
    /**
     * Print the array
     *
     * @param array
     */
    public void printArray(int array []) {
        // loop to pirnt 10 elements on a line
        for(int counter = 0; counter < array.length; counter++) {
            System.out.printf("%5d", array[counter]);
           
            // New line after every 10 elements
            if((counter + 1) % 10 == 0) {
                System.out.println();
            }
        }
    }

    /**
     * Generate Random number in a given range.
     *
     * @param min
     * @param max
     * @return random number
     */
    public int generateRandom(int min, int max) {
        return random.nextInt(max - min) + min;
    }
   
    /**
     * Fill the array with sequence from 1 to N
     *
     * @param array
     * @param descending if true
     */
    public void fillArray(int array [], boolean descending) {
        if(!descending) {
            for(int i=0; i<array.length; i++) {
                array[i] = i + 1;  // 1 to N
            }
        } else{
            int N = array.length;
            for(int i=0; i<array.length; i++) {
                array[i] = N--;
            }
        }
    }    
}

Case.java

/**
 *
 * @author CodingHelpLine
 * Web: https://codinghelpline.org
 */
public enum Case {
    WorstCase,
    BestCase,
    AverageCase;
}

SelectionSort.java

/**
 * Implementation of Selection Sort Algorithm.
 *
 * @author CodingHelpLine
 * Web: https://codinghelpline.org */
public class SelectionSort {
   
    // number of swaps
    private int numSwaps;
   
    // number of comparisons
    private int numComparisons;
   
    // Time
    private long startTime;
    private long endTime;
   
    // Array to hold number
    private int array [];
   
    // Fill Array Object
    private FillArray fillArray;
   
   
    /**
     *
     * @param min minimum value
     * @param max maximum value
     * @param size of array
     * @param sortCase  best, worst and average case
     */
    public SelectionSort(int min, int max, int size, Case sortCase) {
        startTime = System.currentTimeMillis();
       
        // allocation
        this.array = new int[size];
       
        // fill object
        this.fillArray = new FillArray();
       
        // Base on case we fill the array
        if(sortCase == Case.BestCase) { // sorted 1 - N
            this.fillArray.fillArray(array, false);
        } else if(sortCase == Case.WorstCase) {
            this.fillArray.fillArray(array, true);
        } else {
            this.fillArray.fillArray(array, min, max);
        }
    }
   
    /**
     * Selection sort to sort the array.
     */
    public void sort() {
        int minIndex = 0;
       
        // outer loop that must run N time
        for(int i=0; i<array.length; i++) {
           
            // store min index - assumption
            minIndex = i;
           
            // Inner Loop - to find min item from unsorted array
            for(int j=i+1; j<array.length; j++) {
               
                // Compare - record
                this.numComparisons++;
                if(array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
           
            // Very important - but this will run N time for
            // each of case: Best, Worst and Average
            if(i != minIndex) { // this will avoid unnecessary swaps
                swap(i, minIndex);
            }
        }
       
        endTime = System.currentTimeMillis();
    }
   
    /**
     * Swap the elements and record number of swaps
     */
    public void swap(int x, int y) {
       this.numSwaps++;
       
       int temp = array[x];
       array[x] = array[y];
       array[y] = temp;
    }
   
    /**
     * Print the array
     */
    public void printArray() {
        this.fillArray.printArray(array);
    }
   
    /**
     * Get the number of swaps
     *
     * @return swaps
     */
    public int getSwaps() {
        return this.numSwaps;
    }
   
    /**
     * Get the number of comparisons
     *
     * @return comparisons
     */
    public int getComparisons() {
        return this.numComparisons;
    }
   
    /**
     * Time taken in ms
     *
     * @return time  
     */
    public long getTime() {
        return endTime - startTime;
    }
}

SelectionSortTest.java

/**
 * Driver code to Test the Selection Sort Algorithm.
 *
 * @author CodingHelpLine
 * Web: https://codinghelpline.org
 */
public class SelectionSortTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
   
        // Constants
        final int MIN = 1;
        final int MAX = 5000;
        final int SIZE = 5000;
       
        // Best Case Scenario
        SelectionSort best = new SelectionSort(MIN, MAX, SIZE, Case.BestCase);
       
        // output
        System.out.println("\nBest Case Scenarios:");
        System.out.println("Before Sorting:");
        best.printArray();
       
        // Do the sorting here
        best.sort();
       
        System.out.println("\nAfter Sorting:");
        best.printArray();
        System.out.printf("Number of Comparisons: %d%n", best.getComparisons());
        System.out.printf("Number of Swaps: %d%n", best.getSwaps());
        System.out.printf("Time Taken: %d milliseconds%n", best.getTime());
       
       
        // Worst Case Scenario
        SelectionSort worst = new SelectionSort(MIN, MAX, SIZE,
                Case.WorstCase);
       
        // output
        System.out.println("\nWorst Case Scenarios:");
        System.out.println("Before Sorting:");
        worst.printArray();
       
        // Do the sorting here
        worst.sort();
       
        System.out.println("\nAfter Sorting:");
        worst.printArray();
        System.out.printf("Number of Comparisons: %d%n", worst.getComparisons());
        System.out.printf("Number of Swaps: %d%n", worst.getSwaps());
        System.out.printf("Time Taken: %d milliseconds%n", worst.getTime());


        // Worst Case Scenario
        SelectionSort average = new SelectionSort(MIN, MAX, SIZE,
                Case.AverageCase);
       
        // output
        System.out.println("\nAverage Case Scenarios:");
        System.out.println("Before Sorting:");
        average.printArray();
       
        // Do the sorting here
        average.sort();
       
        System.out.println("\nAfter Sorting:");
        average.printArray();
        System.out.printf("Number of Comparisons: %d%n", average.getComparisons());
        System.out.printf("Number of Swaps: %d%n", average.getSwaps());
        System.out.printf("Time Taken: %d milliseconds%n", average.getTime());

    }
   
}
Views: 3

Leave a Reply

Your email address will not be published. Required fields are marked *