TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
comb_sort.cpp
Go to the documentation of this file.
1
18#include <algorithm>
19#include <cassert>
20#include <iostream>
21
29int FindNextGap(int gap) {
30 gap = (gap * 10) / 13;
31
32 return std::max(1, gap);
33}
34
42void CombSort(int *arr, int l, int r) {
51 int gap = r;
52
54 bool swapped = true;
55
57 while (gap != 1 || swapped) {
59 gap = FindNextGap(gap);
60
61 swapped = false;
62
64 for (int i = l; i < r - gap; ++i) {
65 if (arr[i] > arr[i + gap]) {
66 std::swap(arr[i], arr[i + gap]);
67 swapped = true;
68 }
69 }
70 }
71}
72
73void tests() {
75 int arr1[10] = {34, 56, 6, 23, 76, 34, 76, 343, 4, 76};
76 CombSort(arr1, 0, 10);
77 assert(std::is_sorted(arr1, arr1 + 10));
78 std::cout << "Test 1 passed\n";
79
81 int arr2[8] = {-6, 56, -45, 56, 0, -1, 8, 8};
82 CombSort(arr2, 0, 8);
83 assert(std::is_sorted(arr2, arr2 + 8));
84 std::cout << "Test 2 Passed\n";
85}
86
88int main() {
90 tests();
91
93 int n;
94 std::cin >> n;
95 int *arr = new int[n];
96 for (int i = 0; i < n; ++i) std::cin >> arr[i];
97 CombSort(arr, 0, n);
98 for (int i = 0; i < n; ++i) std::cout << arr[i] << ' ';
99 delete[] arr;
100 return 0;
101}
void CombSort(int *arr, int l, int r)
Definition comb_sort.cpp:42
void tests()
Definition comb_sort.cpp:73
int main()
Definition comb_sort.cpp:88
int FindNextGap(int gap)
Definition comb_sort.cpp:29