From 6be1c352b2ccf6c081f4a2a2e31bdcdb8958c386 Mon Sep 17 00:00:00 2001 From: Satyam Singh <56315878+satcasm@users.noreply.github.com> Date: Sun, 7 Feb 2021 05:59:55 +0530 Subject: [PATCH] added shell sort (#61) * 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 --- sorting/README.md | 2 ++ sorting/c-or-cpp/shell-sort.cpp | 52 +++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 sorting/c-or-cpp/shell-sort.cpp diff --git a/sorting/README.md b/sorting/README.md index 4c14a06b..56c50cdd 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -10,6 +10,8 @@ 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. [Shell Sort](c-or-cpp/shell-sort.cpp) + ### C# diff --git a/sorting/c-or-cpp/shell-sort.cpp b/sorting/c-or-cpp/shell-sort.cpp new file mode 100644 index 00000000..deeb43af --- /dev/null +++ b/sorting/c-or-cpp/shell-sort.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; +void shellSort(int a[], int n); + +// Driver Code +int main() +{ + cout<<"Enter the length of array"<>n; + int *a = new int(n); + // Getting elements of array + cout<<"Enter the elements of array"<>a[i]; + cout << "Original array: \n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + shellSort(a,n); + cout << "\nSorted array: \n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + delete (a); + return 0; +} + +void shellSort(int a[], int n) +{ + // Starting with a big gap, then reducing the gap + for (int gap = n/2; gap > 0; gap /= 2) + { + // insertion sort for this gap size. + for (int i = gap; i < n; i += 1) + { + // add a[i] to the elements that have been gap sorted + // save a[i] in temp and make a hole at position i + int temp = a[i]; + + // shift earlier gap-sorted elements up until the correct + // location for a[i] is found + int j; + for (j = i; j >= gap && a[j - gap] > temp; j -= gap) + a[j] = a[j - gap]; + + // put temp (the original a[i]) in its correct location + a[j] = temp; + } + } +} + + +