forked from ccgcv/Cplus-plus-for-hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection_sort.cpp
More file actions
44 lines (37 loc) · 831 Bytes
/
selection_sort.cpp
File metadata and controls
44 lines (37 loc) · 831 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;
int main()
{
// n is the number of elements in the array
int n;
cin>>n;
vector <int> v(n);
// Taking user input
for(int i=0; i<n; i++)
{
cin>>v[i];
}
// Performing selection sort
for(int i=0; i<n-1; i++)
{
int min_index = i;
// Iterating to find if there exists a smaller element in the unsorted segment
for(int j=i+1; j<n; j++)
{
if(v[j]<v[min_index])
{
min_index = j;
}
}
// If there exists a smaller element then swapping the values
if(min_index != i)
{
swap(v[i],v[min_index]);
}
}
// Output of the sorted array
for(int i=0; i<n; i++)
{
cout<<v[i]<<" ";
}
}