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:
- for loop
- DSA Sorting Technique
ALGORITHM FOR SELECTION SORTING IN C++.
Let ARR is an array having N elements
- Read ARR
- Repeat step 3 to 6 for I=0 to N-1
- Set MIN=ARR[I] and Set LOC=I
- Repeat step 5 for J=I+1 to N
- If MIN>ARR[J], then
(a) Set MIN=ARR[J]
(b) Set LOC=J
[End of if]
[End of step 4 loop]
- Interchange ARR[I] and ARR[LOC] using the temporary variable
[End of step 2 outer loop]
- 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
- C++ Programs To Create a Pyramid and Pattern
- C++ Program to Check Whether a Number is Prime or Not
- C++ Program to display Amstrong Number between Two intervals.
- C++ Program to create a Pyramid and Pattern.
- C++ Program to display the Prime number between two intervals using Functions.
- C++ Program to Check Prime Number by creating a function.
- C++ Program to check whether a number can be express as Sum of Two Prime Numbers.
- C++ Program to find the sum of natural numbers using recursion.
- C++ Program to Find Transpose of a Matrix
- 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.