Skip to content

Commit 55ef68e

Browse files
authored
Merge pull request deutranium#194 from rcchcz/shellSortCPP
ShellSort in C++
2 parents 8696129 + 1fd6ff1 commit 55ef68e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

sortingAlgo/ShellSort/ShellSort.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <vector>
2+
#include <algorithm>
3+
#include <iostream>
4+
5+
/**
6+
* This function implements the Shell Sorting Algorithm.
7+
*
8+
* @note Knuth sequence was used.
9+
*
10+
* @param v Vector to be sorted.
11+
*/
12+
void shellSort(std::vector<int> &v) {
13+
int gap;
14+
// calculate the first gap, based on Knuth sequence
15+
for(gap = 1; gap < (v.end() - v.begin()); gap = 3 * gap + 1);
16+
while(gap > 0) { // change to while(gap)
17+
// descrease the gap
18+
gap = (gap - 1)/3;
19+
// pass by elements to swap then if necessary
20+
for(size_t i = 0; v.begin() + gap + i < v.end(); i++) {
21+
if(*(v.begin() + gap + i) < *(v.begin() + i)) {
22+
std::swap(*(v.begin() + gap + i), *(v.begin() + i));
23+
// in case some element was sawpped, it will try swap the elements before, maintaining the gap
24+
for(int j = i - gap; j >= 0; j -= gap) {
25+
if(*(v.begin() + gap + j) < *(v.begin() + j)) { std::swap(*(v.begin() + gap + j), *(v.begin() + j)); }
26+
}
27+
}
28+
}
29+
30+
}
31+
}
32+
33+
/**
34+
* Simple print function.
35+
*/
36+
void printVec(std::vector<int> v) {
37+
for(int i = 0; i < v.size(); i++) std::cout << v[i] << " ";
38+
std::cout << std::endl;
39+
}
40+
41+
/**
42+
* Driver code.
43+
*/
44+
int main() {
45+
std::vector<int> v = {23, -10, 20, -11, 12, -6, 7, 299, 9, -1, 37, 51, 0};
46+
shellSort(v);
47+
std::cout << "Sorted: ";
48+
printVec(v);
49+
50+
return 0;
51+
}

0 commit comments

Comments
 (0)