Skip to content

Commit 8881ea8

Browse files
committed
feat: selection sort in c++
1 parent 70583e6 commit 8881ea8

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Diff for: sortingAlgo/selectionSort/selectionSort.cc

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include<iostream>
2+
#include<algorithm>
3+
4+
using namespace std;
5+
6+
void selectionsort(int a[], int n) {
7+
for(int i = 0; i < n-1; ++i) {
8+
int min = i;
9+
for(int j = i+1; j < n; ++j) {
10+
if(a[j] < a[min])
11+
min = j;
12+
}
13+
14+
swap(a[min], a[i]);
15+
}
16+
}
17+
18+
int min_i(int a[], int i, int j) {
19+
if(i == j) return i;
20+
21+
int k = min_i(a, i+1, j);
22+
return (a[i] < a[k]) ? i : k;
23+
}
24+
25+
void selectionsort_rec(int* a, int b, int e=0) {
26+
if(b == e) return;
27+
28+
int key = min_i(a, e, b-1);
29+
if(key != e)
30+
swap(a[key], a[e]);
31+
32+
selectionsort_rec(a, b, e+1);
33+
}
34+
35+
int main() {
36+
int arr[] = {3,450,12,4,-1,0,24,95,123,0};
37+
for(int i = 0; i < 10; ++i) {
38+
cout << *(arr+i) << ' ';
39+
}
40+
cout << endl;
41+
selectionsort_rec(arr, 10);
42+
for(int i = 0; i < 10; ++i) {
43+
cout << *(arr+i) << ' ';
44+
}
45+
return 0;
46+
}

0 commit comments

Comments
 (0)