-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSelection sort.cpp
More file actions
43 lines (38 loc) · 1.01 KB
/
Copy pathSelection sort.cpp
File metadata and controls
43 lines (38 loc) · 1.01 KB
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
/* In selection sort, first we select the smallest element and swap it to the first position,
then we choose the smallest element in the remaining sub-array and swap it to the 2nd position
and so on until the length of sub-array becomes one */
#include <iostream>
#include <cstdio>
using namespace std;
void selectionSort(int* arr, int size) {
int first = 0;
while(first < size) {
int smallest = first;
for(int i=first+1; i<size; i++) {
if(arr[smallest] > arr[i])
smallest = i;
}
int temp = arr[first];
arr[first] = arr[smallest];
arr[smallest] = temp;
++first;
}
return;
}
void printArr(int* arr, int size) {
for(int i=0; i<size; i++)
cout<<arr[i]<<endl;
return;
}
int main() {
freopen("input.txt","r",stdin);
int size;
cin>>size;
int arr[size];
for(int i=0; i<size; i++)
cin>>arr[i];
cout<<"Selection sort: "<<endl;
selectionSort(arr, size);
printArr(arr, size);
return 0;
}