Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.
- First we find the smallest element and swap it with the first element. This way we get the smallest element at its correct position.
- Then we find the smallest among remaining elements (or second smallest) and swap it with the second element.
- We keep doing this until we get all elements moved to correct position.
C++
// C++ program to implement Selection Sort
#include <bits/stdc++.h>
using namespace std;
void selectionSort(vector<int> &arr) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; ++j) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller
// element is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
swap(arr[i], arr[min_idx]);
}
}
void printArray(vector<int> &arr) {
for (int &val : arr) {
cout << val << " ";
}
cout << endl;
}
int main() {
vector<int> arr = {64, 25, 12, 22, 11};
cout << "Original array: ";
printArray(arr);
selectionSort(arr);
cout << "Sorted array: ";
printArray(arr);
return 0;
}
C
// C program for implementation of selection sort
#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Java
// Java program for implementation of Selection Sort
import java.util.Arrays;
class GfG {
static void selectionSort(int[] arr){
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element
// is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
static void printArray(int[] arr){
for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
public static void main(String[] args){
int[] arr = { 64, 25, 12, 22, 11 };
System.out.print("Original array: ");
printArray(arr);
selectionSort(arr);
System.out.print("Sorted array: ");
printArray(arr);
}
}
Python
# Python program for implementation of Selection
# Sort
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
# Assume the current position holds
# the minimum element
min_idx = i
# Iterate through the unsorted portion
# to find the actual minimum
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
# Update min_idx if a smaller element is found
min_idx = j
# Move minimum element to its
# correct position
arr[i], arr[min_idx] = arr[min_idx], arr[i]
def print_array(arr):
for val in arr:
print(val, end=" ")
print()
if __name__ == "__main__":
arr = [64, 25, 12, 22, 11]
print("Original array: ", end="")
print_array(arr)
selection_sort(arr)
print("Sorted array: ", end="")
print_array(arr)
C#
// C# program for implementation
// of Selection Sort
using System;
class GfG {
static void selectionSort(int[] arr){
int n = arr.Length;
for (int i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
int min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element
// is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
static void printArray(int[] arr){
foreach(int val in arr){
Console.Write(val + " ");
}
Console.WriteLine();
}
public static void Main(){
int[] arr = { 64, 25, 12, 22, 11 };
Console.Write("Original array: ");
printArray(arr);
selectionSort(arr);
Console.Write("Sorted array: ");
printArray(arr);
}
}
JavaScript
function selectionSort(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
// Assume the current position holds
// the minimum element
let min_idx = i;
// Iterate through the unsorted portion
// to find the actual minimum
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
// Update min_idx if a smaller element is found
min_idx = j;
}
}
// Move minimum element to its
// correct position
let temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
function printArray(arr) {
for (let val of arr) {
process.stdout.write(val + " ");
}
console.log();
}
// Driver function
const arr = [64, 25, 12, 22, 11];
console.log("Original array: ");
printArray(arr);
selectionSort(arr);
console.log("Sorted array: ");
printArray(arr);
PHP
<?php
function selectionSort(&$arr) {
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
// Assume the current position holds
// the minimum element
$min_idx = $i;
// Iterate through the unsorted portion
// to find the actual minimum
for ($j = $i + 1; $j < $n; $j++) {
if ($arr[$j] < $arr[$min_idx]) {
// Update min_idx if a smaller element is found
$min_idx = $j;
}
}
// Move minimum element to its
// correct position
$temp = $arr[$i];
$arr[$i] = $arr[$min_idx];
$arr[$min_idx] = $temp;
}
}
function printArray($arr) {
foreach ($arr as $val) {
echo $val . " ";
}
echo "\n";
}
$arr = [64, 25, 12, 22, 11];
echo "Original array: ";
printArray($arr);
selectionSort($arr);
echo "Sorted array: ";
printArray($arr);
?>
OutputOriginal vector: 64 25 12 22 11
Sorted vector: 11 12 22 25 64
Complexity Analysis of Selection Sort
Time Complexity: O(n2) ,as there are two nested loops:
- One loop to select an element of Array one by one = O(n)
- Another loop to compare that element with every other Array element = O(n)
- Therefore overall complexity = O(n) * O(n) = O(n*n) = O(n2)
Auxiliary Space: O(1) as the only extra memory used is for temporary variables.
Advantages of Selection Sort
- Easy to understand and implement, making it ideal for teaching basic sorting concepts.
- Requires only a constant O(1) extra memory space.
- It requires less number of swaps (or memory writes) compared to many other standard algorithms. Only cycle sort beats it in terms of memory writes. Therefore it can be simple algorithm choice when memory writes are costly.
Disadvantages of the Selection Sort
- Selection sort has a time complexity of O(n^2) makes it slower compared to algorithms like Quick Sort or Merge Sort.
- Does not maintain the relative order of equal elements which means it is not stable.
Applications of Selection Sort
- Perfect for teaching fundamental sorting mechanisms and algorithm design.
- Suitable for small lists where the overhead of more complex algorithms isn't justified and memory writing is costly as it requires less memory writes compared to other standard sorting algorithms.
- Heap Sort algorithm is based on Selection Sort.
Question 1: Is Selection Sort a stable sorting algorithm?
Answer: No, Selection Sort is not stable as it may change the relative order of equal elements.
Question 2: What is the time complexity of Selection Sort?
Answer: Selection Sort has a time complexity of O(n^2) in the best, average, and worst cases.
Question 3: Does Selection Sort require extra memory?
Answer: No, Selection Sort is an in-place sorting algorithm and requires only O(1) additional space.
Question 4: When is it best to use Selection Sort?
Answer: Selection Sort is best used for small datasets, educational purposes, or when memory usage needs to be minimal.
Question 5: How does Selection Sort differ from Bubble Sort?
Answer: Selection Sort selects the minimum element and places it in the correct position with fewer swaps, while Bubble Sort repeatedly swaps adjacent elements to sort the array.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem