C++ Program for Selection Sort

In this article, you will learn and get code to implement selection sort in C++. Here are the list of programs on selection sort, available in this article:

  • Selection Sort in Ascending Order
  • Selection Sort in Descending Order
  • Selection Sort using Function
  • Selection Sort using Class and Object

But before creating these programs, if you're not aware about selection sort, refer to selection sort algorithm and example to get every required things about it.

Selection Sort in C++

To sort an array in ascending order using selection sort technique in C++ programming, you have to ask from user to enter the size and elements for an array. Now sort the array using selection sort technique as shown in the program given below:

Note - Selection sort works in a way that, initially the smallest element gets selected and moved to very first index (0th index, because indexing in arrays starts from 0), then second smallest element gets selected and moved to second (1st) index and so on.

#include<iostream>
using namespace std;
int main()
{
    int tot, arr[50], i, j, temp, small, chk, index;
    cout<<"Enter the Size of Array: ";
    cin>>tot;
    cout<<"Enter "<<tot<<" Array Elements: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];
    for(i=0; i<(tot-1); i++)
    {
        chk=0;
        small = arr[i];
        for(j=(i+1); j<tot; j++)
        {
            if(small>arr[j])
            {
                small = arr[j];
                chk++;
                index = j;
            }
        }
        if(chk!=0)
        {
            temp = arr[i];
            arr[i] = small;
            arr[index] = temp;
        }
    }
    cout<<"\nSorted Array is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample run:

selection sort in C++ Programming

Now enter the size say 10 and then enter any 10 array elements say 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 and press ENTER key to sort the array using selection sort technique, and then print new sorted array as shown in the snapshot given below:

selection sort c++

The dry run of above program with same user input as provided in above sample run, goes like:

  • When user enters 10 as size, then it gets stored in tot. So tot=10
  • And when user enters 10 elements, then it gets stored in arr in this way:
    • arr[0]=10
    • arr[1]=1
    • arr[2]=9
    • and so on upto
    • arr[9]=5
  • Now the execution of second for loop of the program, or the loop that is created to perform the selection sort, begins
  • That is, 0 gets initialized to i and the condition i<(tot-1) or 0<(10-1) or 0<9 evaluates to be true, therefore program flow goes inside the loop
  • Inside the loop, 0 gets initialized to chk. So chk=0
  • And arr[i] or arr[0] or 10 gets initialized to small. So small=10, we've assumed 10 as the smallest element. Now let's compare it with elements at rest indexes
  • Every time we've supposed the element at current index as the smallest element, then compared it with rest of the element, if it is found greater than any element, then we've initialized a new element as the smallest one
  • Now the execution of inner for loop begins. That is, (i+1) or 0+1 or 1 gets initialized to j, and the condition j<tot or 1<10 evaluates to be true, therefore program flow goes inside the loop
  • Inside this loop, the condition (of if) small>arr[j] or 10>arr[1] or 10>1 evaluates to be true, therefore program flow goes inside the if's body
  • And arr[j] or arr[1] or 1 gets initialized to small. The value of chk gets incremented. So chk=1. And finally j or 1 gets initialized to index
  • Now the value of j gets incremented. So j=2 and the condition j<tot or 2<10 evaluates to be true again, therefore program flow again goes inside the loop. This process continues until the condition of this for loop evaluates to be false
  • Because, 1 is the smallest element, therefore small=1 after exiting from this loop. And 1 is at 1st index, therefore index=1
  • After exiting from this loop, the condition (of if) chk!=0 or 1!=0 evaluates to be true, therefore arr[i] or arr[0] or 10 gets initialized to temp, small or 1 gets initialized to arr[i] or arr[0], and finally temp or 10 gets initialized to arr[index] or arr[1]
  • Now the program flow goes to the update part of outer for loop and increments the value of i. So i=1. And the condition again gets evaluated
  • That is the condition i<(tot-1) or 1<(10-1) or 1<9 evaluates to be true again, therefore program flow again goes inside the loop
  • This process continues until the condition evaluates to be false
  • In this way, selection sort gets implemented

To print array after each sort, just place the following block of code:

cout<<"Step "<<i+1<<": ";
for(j=0; j<tot; j++)
    cout<<arr[j]<<" ";
cout<<endl;

after

if(chk!=0)
{
    temp = arr[i];
    arr[i] = small;
    arr[index] = temp;
}

That is, place the code at last inside the for loop that is created to perform selection sort. Now the sample run with same user input as provided in previous sample run, looks like:

c++ selection sort

Selection Sort in Descending Order

To sort an array in descending order using selection sort technique, only replace the condition of if. That is, replace the following condition:

small>arr[j]

with the condition given below

small<arr[j]

Note - Just a matter of greater than (>) and less than (<) sign, whole program gets reversed.

But still, if you want the complete program for selection sort in descending order, then here it is:

#include<iostream>
using namespace std;
int main()
{
    int tot, arr[50], i, j, temp, big, chk, index;
    cout<<"Enter the Size of Array: ";
    cin>>tot;
    cout<<"Enter "<<tot<<" Array Elements: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];
    for(i=0; i<(tot-1); i++)
    {
        chk=0;
        big = arr[i];
        for(j=(i+1); j<tot; j++)
        {
            if(big<arr[j])
            {
                big = arr[j];
                chk++;
                index = j;
            }
        }
        if(chk!=0)
        {
            temp = arr[i];
            arr[i] = big;
            arr[index] = temp;
        }
    }
    cout<<"\nSorted Array in Descending Order is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}

The snapshot given below shows the sample run of this program with user input, 10 as size, and 1, 10, 9, 2, 8, 3, 7, 4, 6, 5 as 10 array elements:

selection sort in descending order c++

Selection Sort using Function

Now let's create another program that does the same job as of very first program. That is this program implements selection sort to sort an array in ascending order, using user-defined function selSort().

The function selSort() takes two arguments. The first argument is the array, whereas the second argument is its size. This function sorts an array using selection sort technique:

#include<iostream>
using namespace std;
void selSort(int [], int);
int main()
{
    int tot, arr[50], i;
    cout<<"Enter the Size of Array: ";
    cin>>tot;
    cout<<"Enter "<<tot<<" Array Elements: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];
    selSort(arr, tot);
    cout<<"\nSorted Array is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}
void selSort(int arr[], int tot)
{
    int i, j, temp, small, chk, index;
    for(i=0; i<(tot-1); i++)
    {
        chk=0;
        small = arr[i];
        for(j=(i+1); j<tot; j++)
        {
            if(small>arr[j])
            {
                small = arr[j];
                chk++;
                index = j;
            }
        }
        if(chk!=0)
        {
            temp = arr[i];
            arr[i] = small;
            arr[index] = temp;
        }
    }
}

This program produces the same output as of very first program of this article. Here is its sample run, with user input 5 as size, and 5, 4, 3, 2, 1 as 5 array elements:

selection sort using function c++

Selection Sort using Class

This is the last program of this article to implement selection sort in C++. This program uses class and object, an object-oriented feature of C++.

#include<iostream>
using namespace std;
class CodesCracker
{
    public:
        void selSort(int [], int);
};
void CodesCracker::selSort(int arr[], int tot)
{
    int i, j, temp, small, chk, index;
    for(i=0; i<(tot-1); i++)
    {
        chk=0;
        small = arr[i];
        for(j=(i+1); j<tot; j++)
        {
            if(small>arr[j])
            {
                small = arr[j];
                chk++;
                index = j;
            }
        }
        if(chk!=0)
        {
            temp = arr[i];
            arr[i] = small;
            arr[index] = temp;
        }
    }
}
int main()
{
    CodesCracker c;
    int tot, arr[50], i;
    cout<<"Enter the Size of Array: ";
    cin>>tot;
    cout<<"Enter "<<tot<<" Array Elements: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];
    c.selSort(arr, tot);
    cout<<"\nSorted Array is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}

An object c is created of type CodesCracker inside the main() function. And using this object, we've called the member function (selSort()) of the class CodesCracker using dot (.) operator. Rest of the things are similar like function.

Same Program in Other Languages

C++ Online Test


« Previous Program Next Program »

Follow/Like Us on Facebook




Subscribe Us on YouTube