Friday, December 27, 2024
Google search engine
HomeData Modelling & AIStable Selection Sort

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 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


Python3




# 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
 

This article is contributed by Shubham Rana. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments