Implement Selection Sort in C++



The selection sort is an in-place comparison-based simple sorting algorithm. In the selection sort technique, the list is divided into two parts: sorted and unsorted. The minimum element from the unsorted part is selected and swapped with the element at the beginning of the list. Similarly, the next minimum value from the unsorted list is placed at the next position in the sorted list, and this keeps repeating until the whole array is sorted.

In this article, we have an unsorted array. Our task is to sort this array using selection sort in C++. Here is an example of selection sort:

Input: 
array = [5, 6, 2, 4, 1]

Output:
Sorted array = [1, 2, 4, 5, 6]

Working of Selection Sort

The following image explains the working of selection sort for the above example.

Selection sort

Steps to Implement Selection Sort

We will follow the steps mentioned below to implement the selection sort in C++.

  • The selectionSort() function sorts the unsorted array. It accepts two arguments i.e. first element and the size of the array.
  • The outer for loop decides the position in the sorted array where elements from the unsorted part are to be placed.
  • The inner for loop gets the minimum element from the unsorted part of the array.
  • The if/else statement checks if the element present at index j is smaller than the current minimum element.
  • The swap() function swaps the element and places the element at its correct position.
  • At the end, the display() function displays the array before and after the sorting.

C++ Program to Implement Selection Sort

Here is the code implementation of the steps mentioned above:

#include<iostream>
using namespace std;

void swapping(int &a, int &b) {  // swap the content of a and b
   int temp;
   temp = a;
   a = b;
   b = temp;
}

void display(int *array, int size) {
   for(int i = 0; i < size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void selectionSort(int *array, int size) {
   int i, j, imin;
   for(i = 0; i < size - 1; i++) {
      imin = i;   // get index of minimum data
      for(j = i + 1; j < size; j++)
         if(array[j] < array[imin])
            imin = j;
      // placing in correct position
      swap(array[i], array[imin]);
   }
}

int main() {
   int arr[] = {5, 6, 2, 4, 1};  // hardcoded array
   int n = sizeof(arr) / sizeof(arr[0]);

   cout << "Array before Sorting: ";
   display(arr, n);
   selectionSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}

The output of the above code is:

Array before Sorting: 5 6 2 4 1 
Array after Sorting: 1 2 4 5 6 

Time and Space Complexities

The time and space complexities of selection sort are as follows:

Updated on: 2025-04-17T16:53:03+05:30

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements