From 5bfa1de2fcd9aba9f943618cc55cca4429e545ea Mon Sep 17 00:00:00 2001 From: Anish <87910771+AnishLohiya@users.noreply.github.com> Date: Wed, 2 Feb 2022 11:03:55 +0530 Subject: [PATCH] chore(C): add shell sort (#678) --- algorithms/C/README.md | 1 + algorithms/C/sorting/shell-sort.c | 51 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 algorithms/C/sorting/shell-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index ecae21ba..77a27dbe 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -51,6 +51,7 @@ - [Heap Sort](sorting/heap-sort.c) - [Selection Sort](sorting/selection-sort.c) - [Quick Sort](sorting/quick-sort.c) +- [Shell Sort](sorting/shell-sort.c) ## Strings diff --git a/algorithms/C/sorting/shell-sort.c b/algorithms/C/sorting/shell-sort.c new file mode 100644 index 00000000..15de8179 --- /dev/null +++ b/algorithms/C/sorting/shell-sort.c @@ -0,0 +1,51 @@ +#include + +// Shell Sort +void ShellSort(int a[], int n) +{ + int i, j, k, temp; + // Rearrange elements at each n/2, n/4, n/8, ... intervals + for (i = n / 2; i > 0; i /= 2) + { + for (j = i; j < n; j++) + { + temp = a[j]; + for (k = j; k >= i && a[k - i] > temp; k -= i) + { + a[k] = a[k - i]; + } + a[k] = temp; + } + } +} + +// Prints the array +void printArray(int a[], int size) +{ + for (int i = 0; i < size; ++i) + { + printf("%d ", a[i]); + } +} + +int main() +{ + int a[] = {64, 25, 12, 22, 11, 90}; + int n = sizeof(a) / sizeof(a[0]); + printf("Array before sorting:\n"); + printArray(a, n); + ShellSort(a, n); + printf("\nArray after sorting:\n"); + printArray(a, n); + return 0; +} + +/* +Output: +Array before sorting: +64 25 12 22 11 90 +Array after sorting: +11 12 22 25 64 90 + +Time Complexity: O(n log n) +*/