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 Case
Average Case
Worst Case
Space Complexity
Selection Sort
O(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.
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
Thanks for your feedback! If you have time, please provide details by selecting options below.
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!