forked from IOSD/Algo
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathselection_sort.cpp
53 lines (43 loc) · 1.01 KB
/
selection_sort.cpp
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
45
46
47
48
49
//Selection Sort
// Time Complexity: O(n^2)
// Space Complexity: O(1)
#include<iostream>
using namespace std;
void selectsort(int p[], int size)
{ //function for selection sort, taking array and its size as arguments
int min,pos,temp;
for(int t=0; t<(size-1); t++)
{ min=p[t];
pos=t;
for( int j=t+1; j<size; j++)
{
if(p[j]<min) //checking the minimum no.
{
min=p[j]; //taking the position of minimum no.
pos=j;
}
}
//swap the minimum no. with the first element ith the runninf loop
temp=p[t];
p[t]=p[pos];
p[pos]=temp;
}
}
int main()
{
int m[50],n,i;
cout<<"Hom many Elements , you want to enter:\n";
cin>>n; //no. of elements in array user want to enter
cout<<"\nEnter the elements:\n";
for( i=0; i<n; i++ )
{
cin>>m[i]; //taking number as input from user
}
selectsort(m,n); //call selectsort function
cout<<"\nSorted Array:\n";
for( i=0; i<n; i++)
{
cout<<m[i]<<"\t"; //display the sorted array
}
return 0;
}