Implementing Selection Sort Algorithm as Java Program


Selection Sort Algo in Java

Like Bubble sort, Selection sort is a simple sorting algorithm. It works on the logic of repeatedly finding the minimum element in an unsorted array and then swapping it with the first unsorted element until the whole array is sorted.

You would require two nested arrays to implement Selection sort in Java.

package org.code2care.java.sorting.algo;

import java.util.Arrays;

/**
 * SelectionSort Example in Java
 *
 * Author: Code2care.org
 * Date: 28 April 2023
 * Version: v1.0
 *
 */
public class SelectionSortJavaExample {

    public static void main(String[] args) {

        //Unsorted Array
        int[] unsortedArray = {4, 99, 2, 11, 34, 67, 54, 12, 45, 245, 234, 12, 200};
        SelectionSortJavaExample selectionSort = new SelectionSortJavaExample();

        int[] sortedArray = selectionSort.selectionSortAlgorithm(unsortedArray);

        System.out.println(Arrays.toString(sortedArray));
    }

    public int[] selectionSortAlgorithm(int[] arrayOfNumbers) {

        int arrayLength = arrayOfNumbers.length;

        for (int i = 0; i < arrayLength - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arrayLength; j++) {
                if (arrayOfNumbers[j] < arrayOfNumbers[minIndex]) {
                    minIndex = j;
                }
            }
            int tempVariable = arrayOfNumbers[minIndex];
            arrayOfNumbers[minIndex] = arrayOfNumbers[i];
            arrayOfNumbers[i] = tempVariable;
        }

        return arrayOfNumbers;
    }
}

Time Complexity
Best CaseAverage CaseWorst CaseSpace Complexity
Selection SortO(n^2)O(n^2)O(n^2)O(1)

As Selection sort has a worst-case time complexity of O(n^2), it is less efficient and recommended to be avoided for larger datasets, it's better to make use of efficient sorting algorithms like Merge sort and Quick sort.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap