C++ Program for Selection Sort

487
views

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

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.

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

Previous articleAndroid Slider Menu
Next articleBasic Linked List Operations
SHARE