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:
Iterative selection sort for linked list
Next article icon

Stable Selection Sort

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 operation so that the comparison of two keys considers position as a factor for objects with equal key or by tweaking it in a way such that its meaning doesn’t change and it becomes stable as well.
Example : 
 

Note: Subscripts are only used for understanding the concept.

Input : 4A 5 3 2 4B 1
Output : 1 2 3 4B 4A 5

Stable Selection Sort would have produced
Output : 1 2 3 4A 4B 5


Selection sort works by finding the minimum element and then inserting it in its correct position by swapping with the element which is in the position of this minimum element. This is what makes it unstable.
Swapping might impact in pushing a key(let’s say A) to a position greater than the key(let’s say B) which are equal keys. which makes them out of desired order. 
In the above example 4A was pushed after 4B and after complete sorting this 4A remains after this 4B. Hence resulting in unstability.
Selection sort can be made Stable if instead of swapping, the minimum element is placed in its position without swapping i.e. by placing the number in its position by pushing every element one step forward(shift all elements to left by 1). 
In simple terms use a technique like insertion sort which means inserting element in its correct place. 
EXPLANATION WITH EXAMPLE: 
 

Example: 4A 5 3 2 4B 1
First minimum element is 1, now instead
of swapping. Insert 1 in its correct place
and pushing every element one step forward
i.e forward pushing.
1 4A 5 3 2 4B
Next minimum is 2 :
1 2 4A 5 3 4B
Next minimum is 3 :
1 2 3 4A 5 4B
Repeat the steps until array is sorted.
1 2 3 4A 4B 5


 


 

C++
// C++ program for modifying Selection Sort // so that it becomes stable. #include <iostream> using namespace std;  void stableSelectionSort(int a[], int n) {     // Iterate through array elements     for (int i = 0; i < n - 1; i++)      {          // Loop invariant : Elements till a[i - 1]         // are already sorted.          // Find minimum element from          // arr[i] to arr[n - 1].         int min = i;         for (int j = i + 1; j < n; j++)             if (a[min] > a[j])                 min = j;          // Move minimum element at current i.         int key = a[min];       //Shift left all elements by one.       for(int k=min;k>i;k--)         a[k]=a[k-1];       //Store the key at its right position.         a[i] = key;     } }  void printArray(int a[], int n) {     for (int i = 0; i < n; i++)         cout << a[i] << " ";     cout << endl; }  // Driver code int main() {     int a[] = { 4, 5, 3, 2, 4, 1 };     int n = sizeof(a) / sizeof(a[0]);     stableSelectionSort(a, n);     printArray(a, n);     return 0; } 
Java
// Java program for modifying Selection Sort // so that it becomes stable. class GFG {     static void stableSelectionSort(int[] a, int n)     {         // Iterate through array elements         for (int i = 0; i < n - 1; i++)          {              // Loop invariant : Elements till              // a[i - 1] are already sorted.              // Find minimum element from              // arr[i] to arr[n - 1].             int min = i;             for (int j = i + 1; j < n; j++)                 if (a[min] > a[j])                     min = j;              // Move minimum element at current i.             int key = a[min];             while (min > i)              {                 a[min] = a[min - 1];                 min--;             }                          a[i] = key;         }     }      static void printArray(int[] a, int n)     {         for (int i = 0; i < n; i++)         System.out.print(a[i]+ " ");                  System.out.println();     }      // Driver code     public static void main (String[] args)      {         int[] a = { 4, 5, 3, 2, 4, 1 };         int n = a.length;         stableSelectionSort(a, n);         printArray(a, n);     } }  // This code is contributed by Mr. Somesh Awasthi 
Python
# Python3 program for modifying Selection Sort # so that it becomes stable. def stableSelectionSort(a, n):          # Traverse through all array elements     for i in range(n):          # Find the minimum element in remaining         # unsorted array         min_idx = i         for j in range(i + 1, n):             if a[min_idx] > a[j]:                 min_idx = j          # Move minimum element at current i         key = a[min_idx]         while min_idx > i:             a[min_idx] = a[min_idx - 1]             min_idx -= 1         a[i] = key  def printArray(a, n):     for i in range(n):         print("%d" %a[i], end = " ")      # Driver Code a = [4, 5, 3, 2, 4, 1] n = len(a) stableSelectionSort(a, n) printArray(a, n)  # This code is contributed  # by Mr. Raju Pitta 
C#
// C# program for modifying Selection Sort // so that it becomes stable. using System;  class GFG {     static void stableSelectionSort(int[] a, int n)     {         // Iterate through array elements         for (int i = 0; i < n - 1; i++)          {              // Loop invariant : Elements till              // a[i - 1] are already sorted.              // Find minimum element from              // arr[i] to arr[n - 1].             int min = i;             for (int j = i + 1; j < n; j++)                 if (a[min] > a[j])                     min = j;              // Move minimum element at current i.             int key = a[min];             while (min > i)              {                 a[min] = a[min - 1];                 min--;             }                          a[i] = key;         }     }      static void printArray(int[] a, int n)     {         for (int i = 0; i < n; i++)         Console.Write(a[i] + " ");                  Console.WriteLine();     }      // Driver code     public static void Main ()      {         int[] a = { 4, 5, 3, 2, 4, 1 };         int n = a.Length;         stableSelectionSort(a, n);         printArray(a, n);     } }  // This code is contributed by vt_m. 
JavaScript
<script> // Javascript program for modifying Selection Sort // so that it becomes stable.     function stableSelectionSort(a, n)     {         // Iterate through array elements         for (let i = 0; i < n - 1; i++)          {                // Loop invariant : Elements till              // a[i - 1] are already sorted.                // Find minimum element from              // arr[i] to arr[n - 1].             let min = i;             for (let j = i + 1; j < n; j++)                 if (a[min] > a[j])                     min = j;                // Move minimum element at current i.             let key = a[min];             while (min > i)              {                 a[min] = a[min - 1];                 min--;             }                            a[i] = key;         }     }             function prletArray(a, n)     {         for (let i = 0; i < n; i++)         document.write(a[i]+ " ");                    document.write("<br/>");     }  // driver function          let a = [ 4, 5, 3, 2, 4, 1 ];         let n = a.length;         stableSelectionSort(a, n);         prletArray(a, n);    </script> 

Output
1 2 3 4 4 5 

Time Complexity: O(N2) // since two nested loops are used the time taken by the algorithm to complete all operation is quadratic.
Auxiliary Space: O(1)// since no extra array is used so the space taken by the algorithm is constant
 


 



Next Article
Iterative selection sort for linked list
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Sorting
  • Insertion Sort
  • selection-sort
Practice Tags :
  • 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