-
Notifications
You must be signed in to change notification settings - Fork 368
/
selection_sort.cpp
55 lines (45 loc) · 1.06 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
50
51
52
53
54
55
#include<iostream>
using namespace std;
//Display function
void display(int array[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << array[i] << "\t";
cout << "\n";
}
//Driver code
int main()
{
//Taking size of array as input
int n;
cout << "ENTER THE SIZE OF ARRAY: : ";
cin >> n;
//Taking elements of array as input
int array[n];
cout << "ENTER THE ELEMENTS: " << endl;
for (int i = 0; i < n; i++)
{
cin >> array[i];
}
//Printing unsorted array
cout << "UNSORTED ARRAY: " << endl;
display(array, n);
int i, j, smallest,temp;
//Selection sort
for (i = 0; i < n-1; i++)
{
smallest= i;
for (j = i+1; j < n; j++){
if (array[j] < array[smallest])
smallest = j;
}
temp = array[smallest];
array[smallest] = array[i];
array[i] = temp;
}
//Printing sorted array
cout << "SORTED ARRAY: \n";
display(array, n);
return 0;
}