TheAlgorithms-C-Plus-Plus/sorting/comb_sort.cpp

50 lines
1.1 KiB
C++
Raw Normal View History

2020-05-26 23:46:24 +08:00
// Kind of better version of Bubble sort.
// While Bubble sort is comparering adjacent value, Combsort is using gap larger
// than 1 Best case: O(n) Worst case: O(n ^ 2)
#include <algorithm>
2018-01-04 02:35:42 +08:00
#include <iostream>
2017-10-15 16:19:32 +08:00
int a[100005];
int n;
2020-05-26 23:46:24 +08:00
int FindNextGap(int x) {
2017-10-15 16:19:32 +08:00
x = (x * 10) / 13;
2020-05-26 23:46:24 +08:00
return std::max(1, x);
2017-10-15 16:19:32 +08:00
}
2020-05-26 23:46:24 +08:00
void CombSort(int a[], int l, int r) {
// Init gap
2017-10-15 16:19:32 +08:00
int gap = n;
2019-08-21 10:10:08 +08:00
2020-05-26 23:46:24 +08:00
// Initialize swapped as true to make sure that loop runs
2017-10-15 16:19:32 +08:00
bool swapped = true;
2020-05-26 23:46:24 +08:00
// Keep running until gap = 1 or none elements were swapped
while (gap != 1 || swapped) {
// Find next gap
2017-10-15 16:19:32 +08:00
gap = FindNextGap(gap);
2019-08-21 10:10:08 +08:00
2017-10-15 16:19:32 +08:00
swapped = false;
// Compare all elements with current gap
2020-05-26 23:46:24 +08:00
for (int i = l; i <= r - gap; ++i) {
if (a[i] > a[i + gap]) {
std::swap(a[i], a[i + gap]);
2017-10-15 16:19:32 +08:00
swapped = true;
}
}
}
}
2020-05-26 23:46:24 +08:00
int main() {
std::cin >> n;
for (int i = 1; i <= n; ++i) std::cin >> a[i];
2017-10-15 16:19:32 +08:00
CombSort(a, 1, n);
2020-05-26 23:46:24 +08:00
for (int i = 1; i <= n; ++i) std::cout << a[i] << ' ';
2017-10-15 16:19:32 +08:00
return 0;
}