Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Recursive Selection Sort
Next article icon

Selection Sort

Last Updated : 09 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

  1. First we find the smallest element and swap it with the first element. This way we get the smallest element at its correct position.
  2. Then we find the smallest among remaining elements (or second smallest) and swap it with the second element.
  3. 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);  ?> 

Output
Original 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.



Next Article
Recursive Selection Sort
author
kartik
Improve
Article Tags :
  • DSA
  • Sorting
  • Medlife
Practice Tags :
  • Medlife
  • Sorting

Similar Reads

  • Selection Sort
    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 a
    8 min read
  • Recursive Selection Sort
    The Selection Sort algorithm sorts maintain two parts. The first part that is already sortedThe second part is yet to be sorted. The algorithm works by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the end of the sorted part. arr[] = 64
    6 min read
  • Time and Space complexity analysis of Selection Sort
    The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already
    2 min read
  • Selection sort in different languages

    • Java Program for Selection Sort
      The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. Algorithm for Selection SortImplementation of Selection Sort in Java is mentioned below: Step 1: Array arr with N sizeStep 2: In
      2 min read

    • C Program for Selection Sort
      The selection sort is a simple comparison-based sorting algorithm that sorts a collection by repeatedly finding the minimum (or maximum) element and placing it in its correct position in the list. It is very simple to implement and is preferred when you have to manually implement the sorting algorit
      4 min read

    • Selection Sort - Python
      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 a
      2 min read

  • Stable Selection Sort
    A sorting algorithm is said to be stable if two objects with equal or same keys appear in the same order in sorted output as they appear in the input array to be sorted.Any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison op
    6 min read
  • Iterative selection sort for linked list
    Given a linked list, the task is to sort the linked list in non-decreasing order by using selection sort.Examples: Input : Linked List = 5 ->3 ->4 ->1 ->2Output : 1 ->2 ->3 ->4 ->5 Input : Linked List = 5 ->4 ->3 ->2Output : 2 ->3 ->4 ->5 Table of Content [E
    15+ min read
  • A sorting algorithm that slightly improves on selection sort
    As we know, selection sort algorithm takes the minimum on every pass on the array, and place it at its correct position.The idea is to take also the maximum on every pass and place it at its correct position. So in every pass, we keep track of both maximum and minimum and array becomes sorted from b
    6 min read
  • Program to sort an array of strings using Selection Sort
    Given an array of strings, sort the array using Selection Sort. Examples: Input : paper true soap floppy flower Output : floppy, flower, paper, soap, true Prerequisite : Selection Sort. C/C++ Code // C++ program to implement selection sort for // array of strings. #include <bits/stdc++.h> #inc
    7 min read
  • Selection sort visualizer using PyGame
    In this article, we will see how to visualize Selection sort using a Python library PyGame. It is easy for the human brain to understand algorithms with the help of visualization. Selection sort is a simple and easy-to-understand algorithm that is used to sort elements of an array by dividing the ar
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences