Skip to content
Home » Blog » C++ Program for Selection Sort

C++ Program for Selection Sort

C++ Selection Sort

In this example, you’ll learn selection sort program using sorting technique.

To nicely understand this C++ Selection Sort Program, you should have the knowledge of following C++ programming topics:

  1. for loop
  2. DSA Sorting Technique

ALGORITHM FOR SELECTION SORTING IN C++.

Let ARR is an array having N elements

  1. Read ARR
  2. Repeat step 3 to 6 for I=0 to N-1
  3. Set MIN=ARR[I] and Set LOC=I
  4. Repeat step 5 for J=I+1 to N
  5. If MIN>ARR[J], then

                (a) Set MIN=ARR[J]

                (b) Set LOC=J

[End of if]

[End of step 4 loop]

  1. Interchange ARR[I] and ARR[LOC] using the temporary variable

 [End of step 2 outer loop]

  1. Exit

Note: All seven steps of the algorithm given above is same for C and C++ Programming Language.

C++ SELECTION SORT PROGRAM

#include<iostream>
 
using namespace std;
 
int main()
{
    int i,j,n,loc,temp,min,a[30];
    cout<<"Enter the number of elements:";
    cin>>n;
    cout<<"\nEnter the elements\n";
 
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
 
    for(i=0;i<n-1;i++)
    {
        min=a[i];
        loc=i;
        for(j=i+1;j<n;j++)
        {
            if(min>a[j])
            {
                min=a[j];
                loc=j;
            }
        }
 
        temp=a[i];
        a[i]=a[loc];
        a[loc]=temp;
    }
 
    cout<<"\nSorted list is as follows\n";
    for(i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }
 
    return 0;
}

Output

Enter the number of elements:8

Enter the elements
12
11
4
5
6
22
98
09

Sorted list is as follows
4 5 6 9 11 12 22 98

OUTPUT ANALYSIS.

As in the above output, we first entered 8 for no of values to be accepted

We inserted all 8 no in Unsorted manner and got output in Sorted order (Ascending order).

TIME COMPLEXITY FOR SELECTION SORT

The time complexity for selection sort programs for both worst case and average case is O (n2) because the number of comparisons for both cases is same.

RELATED PROGRAM

  1. C++ Programs To Create a Pyramid and Pattern
  2. C++ Program to Check Whether a Number is Prime or Not
  3. C++ Program to display Amstrong Number between Two intervals.
  4. C++ Program to create a Pyramid and Pattern.
  5. C++ Program to display the Prime number between two intervals using Functions.
  6. C++ Program to Check Prime Number by creating a function.
  7. C++ Program to check whether a number can be express as Sum of Two Prime Numbers.
  8. C++ Program to find the sum of natural numbers using recursion.
  9. C++ Program to Find Transpose of a Matrix
  10. C++ Program for Implementation of Tic Tac Toe game

Ask your questions and clarify your/others doubts on C++ Selection Sorts Program by commenting. Documentation.