Skip to content

Commit 793ed26

Browse files
authored
Merge pull request #104 from lifesizerobot/master
Alternative selection sort in cpp
2 parents c98ab50 + 4dede0a commit 793ed26

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Sorting/SelectionSortAlt.cpp

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// A fairly verbose implementation of selection sort
2+
3+
#include <iostream>
4+
#include <algorithm>
5+
#include <functional>
6+
7+
inline bool ascending(int x, int y)
8+
{
9+
return x > y;
10+
}
11+
12+
inline bool descending(int x, int y)
13+
{
14+
return x < y;
15+
}
16+
17+
void selection_sort(int *array, std::size_t size, std::function<bool(int, int)> direction)
18+
{
19+
for (std::size_t current_index = 0; current_index < size; ++current_index)
20+
{
21+
// The element we want to swap
22+
int preferred_index = current_index;
23+
24+
for (std::size_t next_index = current_index + 1; next_index < size; ++next_index)
25+
{
26+
if (direction(array[preferred_index], array[next_index]))
27+
preferred_index = next_index;
28+
}
29+
30+
std::swap(array[current_index], array[preferred_index]);
31+
32+
}
33+
}
34+
35+
int main()
36+
{
37+
38+
const std::size_t size = 5;
39+
int array[size] = { 8, 5, 4, 2, 1 };
40+
selection_sort(array, size, ascending);
41+
42+
for (std::size_t i = 0; i < size; ++i)
43+
std::cout << array[i] << '\n';
44+
45+
return 0;
46+
}
47+

0 commit comments

Comments
 (0)