-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombSort.cpp
51 lines (38 loc) · 1.2 KB
/
CombSort.cpp
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
#include <vector>
#include "CombSort.h"
using namespace std;
bool CombSort::Sort(vector<int>& v)
{
unsigned i, j, offset;
int swap;
bool isSorted;
// Exit of less than 2 elements
if (v.size() < 2)
return false;
// The initial offset is the number of sorted array elements.
offset = v.size();
// Outer loop - decreases the offset each time until the offset is 1 and no exchanges occurred.
// Note: the pass where the offset is 1 can run multiple times to allow the sorting of nearby neighbours.
do {
// Update offset
offset = (offset * 8) / 11;
// Do not let the offset become less than 1.
offset = (offset == 0) ? 1 : offset;
// Assume the array is sorted until an exchange occurs.
isSorted = true;
// Inner loop - compare and swap elements that are offset elements apart.
for (i = 0; i <= (v.size() - 1 - offset); i++ ) {
j = i + offset;
// Compare elements at i and j
if (v[i] > v[j]) {
// indicate that the current offset produced a swap
isSorted = false;
// swap elements
swap = v[i];
v[i] = v[j];
v[j] = swap;
}
}
} while (!(isSorted && offset == 1));
return isSorted;
}