From e0194a60d2417c07579d4c554653734853422d82 Mon Sep 17 00:00:00 2001 From: Anish <87910771+AnishLohiya@users.noreply.github.com> Date: Sat, 18 Dec 2021 19:20:37 +0530 Subject: [PATCH] chore(C): add quick sort (#652) --- algorithms/C/README.md | 1 + algorithms/C/sorting/quick-sort.c | 61 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 algorithms/C/sorting/quick-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 071135d7..cddb7614 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -45,6 +45,7 @@ - [Insertion Sort](sorting/insertion-sort.c) - [Heap Sort](sorting/heap-sort.c) - [Selection Sort](sorting/selection-sort.c) +- [Quick Sort](sorting/quick-sort.c) ## Strings diff --git a/algorithms/C/sorting/quick-sort.c b/algorithms/C/sorting/quick-sort.c new file mode 100644 index 00000000..eb30d64b --- /dev/null +++ b/algorithms/C/sorting/quick-sort.c @@ -0,0 +1,61 @@ +// Quick Sort Algorithm in C + +#include + +// Function to swap two elements +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} + +/* This function takes first element as pivot, places the pivot element at its correct position in sorted array, +and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot.*/ +int Partition(int a[], int low, int high) +{ + int pivot = a[low]; + int start = low; + int end = high; + + while (start < end) + { + while (a[start] <= pivot) + start++; + while (a[end] > pivot) + end--; + if (start < end) + { + swap(&a[start], &a[end]); + } + } + swap(&a[low], &a[end]); + return end; +} + +// Recursive function to sort an array using quick sort +void Quicksort(int a[], int low, int high) +{ + if (low < high) + { + int pivot = Partition(a, low, high); + Quicksort(a, low, pivot - 1); + Quicksort(a, pivot + 1, high); + } +} + +int main() +{ + int a[] = {5, 2, 4, 6, 1, 3}; + int n = sizeof(a) / sizeof(a[0]); + Quicksort(a, 0, n - 1); + for (int i = 0; i < n; i++){ + printf("%d ", a[i]); + } + return 0; +} + +/* +Output: +1 2 3 4 5 6 +*/ \ No newline at end of file