C++ Program to Implement Selection Sort

C++ Program to Implement Selection Sort

Sorting is one of the most basic yet essential tasks in computer programming. Whenever you deal with a set of numbers, names, or other data, it often needs to be arranged in a certain order. Sorting makes searching, analyzing, and organizing data much easier. From arranging exam results to sorting product prices on a shopping website, sorting algorithms are at the heart of almost every software system.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

One of the simplest and most popular sorting algorithms in C++ is Selection Sort. It is easy to understand and implement, which makes it perfect for beginners. The main idea behind Selection Sort is quite straightforward: find the smallest element from the unsorted part of the array and place it at the beginning. This process continues until the entire array is sorted.

Selection Sort is not the fastest algorithm for large data sets, but it is one of the best starting points for learning how sorting algorithms think and work. It helps new programmers understand how arrays can be manipulated and how comparisons and swaps are made step by step. Let’s explore a few ways to implement Selection Sort in C++ using predefined data so you can follow along easily.

Program 1: Basic Selection Sort using Loops

This first program shows the basic version of Selection Sort. It uses two simple loops to find the smallest element and place it in its correct position.

#include <iostream>

using namespace std;

int main() {

    int arr[] {64, 25, 12, 22, 11};
    int n = sizeof(arr) / sizeof(arr[0]);

    for (int i = 0; i < n - 1; i++) {

        int minIndex = i;

        for (int j = i + 1; j < n; j++) {

            if (arr[j] < arr[minIndex])
                minIndex = j;

        }

        int temp = arr[minIndex];
        arr[minIndex] = arr[i];
        arr[i] = temp;

    }

    cout << "Sorted array in ascending order: ";

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

    cout << endl;

    return 0;

}

In this program, we start with a predefined array of numbers. The outer loop moves through each element of the array, and the inner loop finds the smallest value in the remaining unsorted part. Once the smallest value is found, it’s swapped with the element at the current position. This process continues until the array is completely sorted in ascending order. The logic is simple to understand and helps beginners visualize how sorting gradually happens one step at a time.

Program 2: Selection Sort in Descending Order

Sometimes, we may want to sort data in descending order instead of ascending order. This version of Selection Sort sorts numbers from largest to smallest by making a simple change in the comparison logic.

#include <iostream>

using namespace std;

int main() {

    int arr[] {29, 10, 14, 37, 13};
    int n = sizeof(arr) / sizeof(arr[0]);

    for (int i = 0; i < n - 1; i++) {

        int maxIndex = i;

        for (int j = i + 1; j < n; j++) {

            if (arr[j] > arr[maxIndex])
                maxIndex = j;

        }

        int temp = arr[maxIndex];
        arr[maxIndex] = arr[i];
        arr[i] = temp;

    }

    cout << "Sorted array in descending order: ";

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

    cout << endl;

    return 0;

}

Here, the only difference is that instead of finding the smallest element, we find the largest element and move it to the front in each pass. By changing the comparison condition from < to >, the program now sorts the numbers in descending order. This version shows how flexible Selection Sort is—just a small change in logic gives you a completely different order.

Program 3: Selection Sort using Recursion

Selection Sort can also be implemented using recursion instead of loops. This version is useful for understanding how recursion can replace repetitive loops in sorting algorithms.

#include <iostream>

using namespace std;

void selectionSortRecursive(int arr[], int n, int index = 0) {

    if (index == n - 1)
        return;

    int minIndex = index;

    for (int j = index + 1; j < n; j++) {

        if (arr[j] < arr[minIndex])
            minIndex = j;

    }

    int temp = arr[minIndex];
    arr[minIndex] = arr[index];
    arr[index] = temp;

    selectionSortRecursive(arr, n, index + 1);

}

int main() {

    int arr[] {45, 12, 23, 9, 30};
    int n = sizeof(arr) / sizeof(arr[0]);

    selectionSortRecursive(arr, n);

    cout << "Sorted array using recursion: ";

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

    cout << endl;

    return 0;

}

In this version, the function selectionSortRecursive() performs the same logic as before, but instead of looping through the array, it calls itself again with the next index. Each recursive call handles one position in the array, ensuring the smallest element is placed in its correct spot before moving to the next. This method helps beginners see how recursion works in practical programming scenarios.

Program 4: Selection Sort for Strings

Selection Sort isn’t limited to numbers. It can also be used to sort strings alphabetically. This program demonstrates how Selection Sort can work with a list of words.

#include <iostream>
#include <string>

using namespace std;

int main() {

    string arr[] {"Zebra", "Cat", "Elephant", "Dog", "Ant"};
    int n = sizeof(arr) / sizeof(arr[0]);

    for (int i = 0; i < n - 1; i++) {

        int minIndex = i;

        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex])
                minIndex = j;
        }

        string temp = arr[minIndex];
        arr[minIndex] = arr[i];
        arr[i] = temp;

    }

    cout << "Words sorted alphabetically: ";

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

    cout << endl;

    return 0;

}

This program uses Selection Sort logic to compare and arrange strings instead of numbers. In C++, strings can be compared alphabetically using < and >. This makes it easy to sort words just like numbers. This example is great for understanding how sorting can work with different data types using the same fundamental logic.

Frequently Asked Questions (FAQ)

This section answers common questions that beginners often ask while learning Selection Sort in C++.

Q1: What is Selection Sort in C++?
Selection Sort is a simple sorting algorithm that repeatedly selects the smallest (or largest) element from the unsorted part of an array and places it in its correct position.

Q2: Is Selection Sort efficient for large data sets?
No, Selection Sort has a time complexity of O(n²), which makes it slower for large data sets. However, it’s excellent for understanding how sorting works.

Q3: What is the difference between Bubble Sort and Selection Sort?
In Bubble Sort, elements are repeatedly swapped if they are in the wrong order, while in Selection Sort, the smallest (or largest) element is selected and swapped once per pass. Selection Sort usually performs fewer swaps.

Q4: Can Selection Sort be used for strings or characters?
Yes, Selection Sort works for both numbers and strings because the comparison logic remains the same. It can arrange words alphabetically just as it sorts numbers.

Q5: Why should beginners learn Selection Sort first?
Because it’s easy to understand, doesn’t require complex data structures, and teaches the core concept of comparison and swapping. It builds a strong foundation for learning more advanced sorting algorithms later.

Conclusion

Selection Sort is one of the easiest sorting algorithms to learn and implement in C++. Although it’s not the fastest, it clearly demonstrates how sorting happens through selection and swapping. It’s perfect for beginners who are learning the basics of algorithm design and want to understand how data can be rearranged efficiently.

In this article, we explored several ways to write a C++ Selection Sort program—using loops, recursion, descending order, and even sorting strings. Each version shows a different side of the same algorithm and helps you build a strong understanding of how sorting works in general.

The best way to learn Selection Sort is to experiment with it. Try changing the data in the arrays, print intermediate steps, and observe how elements move into their correct places. With practice, you’ll gain confidence in both your problem-solving skills and your understanding of sorting algorithms in C++.

Scroll to Top