Selection Sort In C++: Algorithm, Working, And Complexity

Selection Sort in C++

If you are struggling to understand “Selection Sort in C++”, you are not alone. Many students find it confusing to figure out how this algorithm actually works step by step, even after reading definitions multiple times.

The real challenge is not writing the code, but understanding the logic behind selecting the minimum element and placing it in the correct position. Without that clarity, the algorithm feels mechanical and hard to remember.

In this article, I will help you understand Selection Sort simply and practically, so you can not only write the code but also explain it confidently in exams and interviews.

TL;DR: Selection Sort In C++ [H3]

Aspect

Summary

Definition

Selection Sort is a simple algorithm that repeatedly selects the minimum element. It places that element in its correct position step by step.

Working

The array is divided into sorted and unsorted parts. In each pass, the smallest element is found and swapped into place.

Complexity

The time complexity is O(n²) in all cases. It does not improve even if the array is already sorted.

Space And  Stability

It is an in-place algorithm with O(1) space. However, it is not stable as it may change the order of equal elements.

Usage

It is useful for learning and small datasets. It is not suitable for large or performance-critical applications.

What Is The Selection Sort Algorithm?

Selection Sort is a simple comparison-based sorting algorithm that works by repeatedly selecting the smallest element from the unsorted part of the array and placing it at its correct position.

The idea is straightforward, where you have to divide the array into two parts. Among them, one part is already sorted, and another is still unsorted. Initially, the sorted part is empty.

In each step, the algorithm scans the unsorted portion to find the minimum element and swaps it with the first unsorted element. This process gradually expands the sorted portion of the array from left to right.

In other words, instead of repeatedly swapping adjacent elements, Selection Sort focuses on selecting the correct element for each position and placing it there in one swap per iteration.

When Should You Not Use Selection Sort?

  • You should not use Selection Sort when your dataset is large, because it takes the same amount of time no matter how the data is arranged.
  • Avoid it when performance matters, since it cannot take advantage of already sorted or nearly sorted data.
  • Do not choose it in real-world applications where faster algorithms are easily available, as it will slow down your system unnecessarily.
  • You should not use it when stability is important, because it may change the relative order of equal elements.
  • Avoid it in time-sensitive systems, such as real-time applications, where consistent but slow performance is a drawback.
  • It is not a good fit when user experience depends on speed, like in search results or dynamic data displays.

When working with arrays, like the large ones, memory management becomes important. Understanding Dynamic Memory Allocation will help you handle arrays more efficiently when implementing sorting algorithms.

What Is The Pseudo-Code Of Selection Sort Algorithm?

When I mentor my students, I always try to make them understand how Selection Sort works at a logical level before jumping into the actual implementation. To do so, I use the Pseudo-code of Selection Sort.

The Pseudo-code helps you see the exact flow of the algorithm without worrying about C++ syntax. Let us break it down in a clean and structured way.

				
					function selectionSort(a, n):
    for i = 0 to n - 2
        minIndex = i
        for j = i + 1 to n - 1
            if a[j] < a[minIndex]
                minIndex = j
        swap a[i] and a[minIndex]
end function

				
			

Explanation Of The Pseudo-code:

  • The outer loop runs (n – 1) times because after placing the first (n – 1) elements correctly, the last element is automatically sorted.
  • Instead of assuming the first element as the minimum value directly, we track its index (minIndex), which makes swapping easier and cleaner.
  • The inner loop scans only the unsorted part of the array.
  • Only one swap is done per pass, which is a key characteristic of Selection Sort.

 

What Is The Step-By-Step Working Of Selection Sort Algorithm?

Now that you understand the basic idea of Selection Sort, I can show you how selection sort actually works in practice. Think of this as a guided dry run so you can clearly see how the algorithm behaves step by step.

Here, I will take a small unsorted array and gradually turn it into a sorted one. Let us consider the array [2, 3, 1].

Step 1: Start With The First Position

We begin by assuming the first element (2) is the minimum. Then we compare it with the remaining elements (3 and 1). After checking all elements, we find that 1 is the smallest value.

The visual represent the first step of selection sort where we will pick up the smallest element from the array and swap to get its correct position

So, we swap 1 with 2. The array now becomes like [1, 3, 2]. Here, the first position is now sorted.

Step 2: Move To The Next Position

Now, we focus on the second element (3) and assume it is the minimum. We compare it with the remaining element (2). Since 2 is smaller than 3, we update the minimum and swap them.

The image shows the second step of the selection sort where we will pick the next minimum one and swap its position to the second place

The array now becomes the [1, 2, 3]. In this step, the second position is now sorted.

Step 3: Final Check

At this point, only one element is left, and it is already in the correct position. So, the array is fully sorted, and no further steps are required.

The image showing the final result of the selection sort where the entire array is now sorted and no more swapping is needed

Step-By-Step Dry Run Table:

Steps

Current Array

Minimum Element

Action

New Array

1

[2, 3, 1]

1

Swap 2 and 1

[1, 3, 2]

2

[1, 3, 2]

2

Swap 3 and 2

[1, 2, 3]

3

[1, 2, 3]

NA

No action needed

[1, 2, 3]

How To Implement Selection Sort In C++?

Now that you have understood how Selection Sort works step by step, it is time to bring that logic into code. I always advise my mentees not to just copy the program, but instead try to relate each line to the dry run.

If your logic is clear, writing the C++ implementation will become simple and fully under your control.

				
					#include <iostream>
using namespace std;

void selectionSort(int arr[], int n) {
    for(int i = 0; i < n; i++) {

        int minIndex = i; // Assume current index is minimum

        // Find actual minimum in remaining array
        for(int j = i + 1; j < n; j++) {
            if(arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }

        // Swap the found minimum with the current position
        int temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
}

void printArray(int arr[], int n) {
    for(int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int arr[] = {2, 3, 10, 4, 1};
    int n = sizeof(arr)/sizeof(arr[0]);

    cout << "Unsorted Array: ";
    printArray(arr, n);

    selectionSort(arr, n);

    cout << "Sorted Array: ";
    printArray(arr, n);

    return 0;
}
				
			

Steps Of The Program:

  • First, inside the main() function, an array is declared with elements in an unsorted order.
  • Then, the program calls the printArray() function to display the unsorted array as it is.
  • After that, the selectionSort() function is called. In this function, the algorithm starts by assuming the current element (starting from index 0) as the minimum.
  • A loop is used to compare this element with the remaining elements of the array. If a smaller element is found, the position of the minimum element is updated.
  • Once the smallest element in that pass is found, it is swapped with the current position using a temporary variable. This process continues for the rest of the array until all elements are sorted.
  • Finally, the printArray() function is called again to display the sorted array.

Output:

The Output image showing the Unsorted array which will get converted to sorted array using the Selection Sort algorithm in C++

From the above output, we can see that the unsorted array is printed first. After performing all the operations, the array becomes the sorted one & it is printed. Hence, the Selection Sort Algorithm is working fine.

 

What Are The Time And Space Complexities Of Selection Sort In C++?

As someone who has mentored students in Data Structures for over a decade, I can tell you that writing Selection Sort is easy, but understanding its complexity is what actually builds your problem-solving strength.

In interviews and real-world coding, this is exactly what separates an average answer from a strong one. So let us break it down simply and practically so that you can remember without confusion.

Time Complexity:

  • The time complexity of Selection Sort is O(n²) in all cases, like best, average, and worst.
  • This happens because for every element, the algorithm scans the remaining unsorted part of the array to find the minimum element.
  • Even if the array is already sorted, it will still perform all comparisons, which is why the complexity does not improve.

Space Complexity:

  • The space complexity of Selection Sort is O(1).
  • This is because it is an in-place sorting algorithm, meaning it does not require any extra memory apart from a few variables used for swapping.

 

Comparison Table Between The Selection Sort And Bubble Sort:

Oftentimes, students ask me that they are getting confused between the Selection Sort and Bubble Sort, as they look similar and solve the same problem. Then, I have to tell them that their work is different.

To make them understand the difference more clearly, I designed the following comparison table between them. If you get this comparison clear now, it will save you confusion later when you move to advanced algorithms.

Criteria

Selection Sort

Bubble Sort

Strategy

Selection

Swapping

Comparisons

Fixed

Repeated

Swaps

Minimum

Maximum

Stability

Unstable

Stable

Adaptiveness

No

Yes

Best Case

Same

Faster

Passes

Limited

Dynamic

What Are Some Real-World Usage Of Selection Sort Algorithm?

From my experience, I can say that Selection Sort is not about performance; it is about control and simplicity. That is why it still has its place in learning environments and small-scale systems.

If you understand where it fits, you will know when a simple solution is actually the right one. Let us check some of its real-world usages.

  • It is commonly used in classrooms to teach sorting concepts because each step is easy to follow and explain.
  • It works well with small datasets, such as sorting a short list, where using complex algorithms would be unnecessary.
  • It is useful in systems where minimizing swaps is important, such as memory-limited or hardware-level operations.
  • It can be applied when you only need a few of the smallest elements, since you can stop the process early after finding them.
  • It is helpful in embedded systems where predictable behavior is more important than speed.

While selection sort is simple and easy to understand, it is not very efficient for large datasets. That is why developers often use faster algorithms like the Quick Sort Algorithm, which can handle bigger inputs more efficiently.

If you keep one thing in mind, that Selection Sort is simple but not scalable, you will make much better decisions in real projects.

 

Common Mistakes Students Make With Selection Sort In C++:

When students first learn Selection Sort in C++, they usually understand the basic idea quickly, but they often miss small logical details. These small mistakes don’t always show up immediately, but they can lead to incorrect sorting or inefficient code.

From my experience teaching DSA for years, most of these errors are not difficult; they happen because students rush through implementation without fully understanding the flow.

  • Students often forget to update the index of the minimum element during each pass, which leads to incorrect sorting.
  • Many beginners swap elements inside the inner loop instead of after finding the minimum element, which breaks the core logic of Selection Sort.
  • Some students write unnecessary swaps even when the minimum element is already in the correct position, leading to avoidable operations.
  • A common mistake is using incorrect loop boundaries, especially in the inner loop, which may skip elements or cause out-of-bounds errors.
  • Students sometimes confuse Selection Sort with Bubble Sort and start comparing adjacent elements instead of finding the minimum element.
  • Many learners do not dry run their code, so they miss logical errors that could be easily caught by stepping through the algorithm.

To write better and cleaner Selection Sort code in C++, you should follow a few simple but practical habits. These will help you avoid the mistakes mentioned above and build strong fundamentals.

  • Always track the index of the minimum element and update it correctly during each iteration.
  • Perform the swap only once per outer loop, after the minimum element is found.
  • Add a condition to avoid swapping when the element is already in the correct position.
  • Be careful with loop limits to ensure all elements are properly compared.
  • Practice dry-running your code with small examples to clearly understand each step.

Conclusion:

Now that you have learned “Selection Sort in C++”, the goal is not just to remember the code, but to truly understand how the algorithm works step by step.

If you are clear with the idea of selecting the minimum element and placing it in the correct position, you will find it much easier to understand other sorting algorithms as well.

Selection sort is one of the basic sorting algorithms, but it is not the only one you should know. To understand how different sorting techniques compare, you can also explore How Bubble Sort Works in C++, which follows a different approach to arranging elements step by step.

 

Takeaways:

  • Selection Sort works by repeatedly finding the smallest element from the unsorted part and placing it at the correct position.
  • It performs only one swap per pass, which makes it simple but not efficient for large datasets.
  • The time complexity remains O(n²) in all cases, whether the array is sorted or not.
  • Selection Sort is an in-place algorithm, meaning it does not require extra memory.
  • It is not a stable sorting algorithm because it may change the order of equal elements.
  • This algorithm is best suited for learning and small datasets, not for real-world performance-critical applications.

 

Frequently Asked Questions:

1) Is Selection Sort stable?

No, Selection Sort is not a stable algorithm. It may change the relative order of equal elements during swapping. This happens because it directly swaps elements without preserving their original positions.

2) What is the time complexity of Selection Sort?

The time complexity of Selection Sort is O(n²) in all cases. It performs the same number of comparisons regardless of input order. This makes it inefficient for large datasets.

3) Is Selection Sort in-place?

Yes, Selection Sort is an in-place sorting algorithm. It does not require any extra memory apart from a few variables. All sorting is done within the original array itself.