From 6526860e530a959f4be0290c32868d2b52f56b51 Mon Sep 17 00:00:00 2001 From: Satyam Singh <56315878+satcasm@users.noreply.github.com> Date: Tue, 9 Feb 2021 18:57:24 +0530 Subject: [PATCH] added comp sort in cpp (#66) * add binary search in js * added merge sort in c * added quick sort in cpp * modified quick sort * added heap sort * updated readme.md * added counting sort * added bucket sort * added shell sort * added comb sort --- sorting/README.md | 4 +- sorting/c-or-cpp/comb-sort.cpp | 67 ++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 sorting/c-or-cpp/comb-sort.cpp diff --git a/sorting/README.md b/sorting/README.md index 0372fce9..91a7bcda 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -10,8 +10,10 @@ 6. [Heap Sort](c-or-cpp/heap-sort.cpp) 7. [Counting Sort](c-or-cpp/counting-sort.cpp) 8. [Bucket Sort](c-or-cpp/bucket-sort.cpp) -9. [Radix Sort](c-or-cpp/radix-sort.cpp) +9. [Radix Sort](c-or-cpp/radix-sort.cpp) 10. [Shell Sort](c-or-cpp/shell-sort.cpp) +11. [Comb Sort](c-or-cpp/comb-sort.cpp) + ### C# diff --git a/sorting/c-or-cpp/comb-sort.cpp b/sorting/c-or-cpp/comb-sort.cpp new file mode 100644 index 00000000..44eae110 --- /dev/null +++ b/sorting/c-or-cpp/comb-sort.cpp @@ -0,0 +1,67 @@ +#include +using namespace std; +int nextGap(int gap); +void combSort(int a[], int n); + +// Driver program +int main() +{ + cout << "Enter the length of array" << endl; + int n; + cin >> n; + int *a = new int(n); + // Getting elements of array + cout << "Enter the elements of array" << endl; + for (int i = 0; i < n; i++) + cin >> a[i]; + cout << "Original array: \n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + combSort(a, n); + cout << "\nSorted array: \n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + delete (a); + return 0; +} + +int nextGap(int gap) +{ + // Shrink gap by Shrink factor + gap = (gap * 10) / 13; + if (gap < 1) + return 1; + return gap; +} + +void combSort(int a[], int n) +{ + // Initialize gap + int gap = n; + + // Initialize swapped as true to make sure that + // loop runs + bool isSwapped = true; + + // Keep running while gap is more than 1 and last + // iteration caused a swap + while (gap != 1 || isSwapped == true) + { + // Find next gap + gap = nextGap(gap); + + // Initialize swapped as false so that we can + // check if swap happened or not + isSwapped = false; + + // Compare all elements with current gap + for (int i = 0; i < n - gap; i++) + { + if (a[i] > a[i + gap]) + { + swap(a[i], a[i + gap]); + isSwapped = true; + } + } + } +}