-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathselection_sort.cpp
More file actions
41 lines (35 loc) · 787 Bytes
/
selection_sort.cpp
File metadata and controls
41 lines (35 loc) · 787 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
#include <iostream>
#include <algorithm>
using namespace std;
void selection_sort(int arr[], int n)
{
int i, j, min_idx;
// move boundary of unsorted sub-array
for (i=0; i < n-1; ++i)
{
//find min element in unsorted array
min_idx = i;
for(j = i+1; j < n; ++j)
{
if (arr[j] < arr[min_idx])
{
min_idx = j;
}
}
//swap found min element with the boundary element
swap(arr[min_idx], arr[i]);
}
}
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
selection_sort(arr, n);
printf("selection sort:\n");
for (int i = 0; i < n; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}