-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorting.cc
75 lines (65 loc) · 1.97 KB
/
Sorting.cc
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <iterator>
#include <vector>
/* Bubble Sort
*
* Compare two values in the data structure.
* If left > right - then swap 2 elements.
* Continue till the end of the elements,
* which, at the time, would have moved the
* largest element to the end.
*/
template <typename T>
void bubble_sort(T first, T last) {
typename std::iterator_traits<T>::difference_type size = std::distance(first, last);
for(int i=0; i<size; ++i) {
T start = first;
for(int j=0; j<size-i-1; ++j) {
typename std::iterator_traits<T>::value_type left = *start;
typename std::iterator_traits<T>::value_type right = *(start+1);
if (left > right) {
*start = right;
*(start+1) = left;
}
++start;
}
}
}
template <typename T>
void selection_sort(T first, T last) {
std::cout << "Selection Sort" << std::endl;
typename std::iterator_traits<T>::difference_type size = std::distance(first, last);
for(int i=0; i<size; ++i) {
T start = first+i;
T min_pos = start;
for(int j=i; j<size; ++j) {
if (*min_pos > *start){
min_pos = start;
}
++start;
}
// swap min pos to ith pos
typename std::iterator_traits<T>::value_type temp = *min_pos;
*min_pos = *(first+i);
*(first+i) = temp;
}
}
int main() {
std::vector<int> input;
std::vector<int>::iterator it;
input.push_back(2);
input.push_back(4);
input.push_back(5);
input.push_back(1);
std::cout << "Before:";
for(it = input.begin(); it != input.end(); ++it)
std::cout << " " << *it;
std::cout << std::endl;
//bubble_sort(input.begin(), input.end());
selection_sort(input.begin(), input.end());
std::cout << "After:";
for(it = input.begin(); it != input.end(); ++it)
std::cout << " " << *it;
std::cout << std::endl;
return 0;
}