From 54dd3310933dcef8990b65bf73840f8040a9532e Mon Sep 17 00:00:00 2001 From: nghiaxlee Date: Sun, 15 Oct 2017 10:19:32 +0200 Subject: [PATCH 1/3] Comb Sort algorithm --- combsort.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 combsort.cpp diff --git a/combsort.cpp b/combsort.cpp new file mode 100644 index 000000000..8b29ffc9d --- /dev/null +++ b/combsort.cpp @@ -0,0 +1,41 @@ +#include + +using namespace std; + +int a[100005]; +int n; + +int FindNextGap(int x) { + x = (x * 10) / 13; + + return max(1, x); +} + +void CombSort(int a[], int l, int r) { + int gap = n; + bool swapped = true; + + while (gap != 1 || swapped) { + gap = FindNextGap(gap); + + swapped = false; + + for(int i = l; i <= r - gap; ++i) { + if (a[i] > a[i + gap]) { + swap(a[i], a[i + gap]); + swapped = true; + } + } + } +} + +int main() { + ios_base::sync_with_stdio(false); cin.tie(NULL); + cin >> n; + for(int i = 1; i <= n; ++i) cin >> a[i]; + + CombSort(a, 1, n); + + for(int i = 1; i <= n; ++i) cout << a[i] << ' '; + return 0; +} \ No newline at end of file From 98ab1c88d903c5af4096be1d705074d9ea06116c Mon Sep 17 00:00:00 2001 From: Le Minh Nghia Date: Mon, 23 Oct 2017 09:57:46 +0200 Subject: [PATCH 2/3] Add comment to make easier to understand --- combsort.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/combsort.cpp b/combsort.cpp index 8b29ffc9d..6c1f3e22b 100644 --- a/combsort.cpp +++ b/combsort.cpp @@ -1,3 +1,8 @@ +//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 using namespace std; @@ -12,14 +17,20 @@ int FindNextGap(int x) { } void CombSort(int a[], int l, int r) { + //Init gap int gap = n; + + //Initialize swapped as true to make sure that loop runs bool swapped = true; + //Keep running until gap = 1 or none elements were swapped while (gap != 1 || swapped) { + //Find next gap gap = FindNextGap(gap); - + swapped = false; + // Compare all elements with current gap for(int i = l; i <= r - gap; ++i) { if (a[i] > a[i + gap]) { swap(a[i], a[i + gap]); @@ -38,4 +49,4 @@ int main() { for(int i = 1; i <= n; ++i) cout << a[i] << ' '; return 0; -} \ No newline at end of file +} From 51caf366c917e002ac582415293a488c5ebf2410 Mon Sep 17 00:00:00 2001 From: Le Minh Nghia Date: Wed, 3 Jan 2018 19:35:42 +0100 Subject: [PATCH 3/3] Replace library --- combsort.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/combsort.cpp b/combsort.cpp index 6c1f3e22b..7aa65ab80 100644 --- a/combsort.cpp +++ b/combsort.cpp @@ -3,7 +3,7 @@ //Best case: O(n) //Worst case: O(n ^ 2) -#include +#include using namespace std; @@ -41,7 +41,6 @@ void CombSort(int a[], int l, int r) { } int main() { - ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for(int i = 1; i <= n; ++i) cin >> a[i];