From 65e1d62d1577447d8b5987b1b915554bb9913af9 Mon Sep 17 00:00:00 2001 From: yashladha Date: Wed, 15 Mar 2017 19:11:18 +0530 Subject: [PATCH] Added Quick Select [C] Closes https://github.com/iiitv/algos/issues/10 --- README.md | 1 + quick_select/quick_select.c | 60 +++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 quick_select/quick_select.c diff --git a/README.md b/README.md index 0539dfd1..a7e928da 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Community (college) maintained list of algorithm implementations and codes. | [Euclidean GCD](https://en.wikipedia.org/wiki/Euclidean_algorithm) | [\[X\]](euclidean_gcd/euclidean_gcd.c) | | [\[X\]](euclidean_gcd/EuclideanGCD.java) | [\[X\]](euclidean_gcd/euclidean_gcd.py) | | [Linear Search](https://en.wikipedia.org/wiki/Linear_search) | | | | [\[X\]](linear_search/linear_search.py) | | [Longest Common Subsequence](http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence) | [\[X\]](longest_common_subsequence/longestCommonSubsequence.c) | | | | +| [Quick Select](https://en.wikipedia.org/wiki/Quickselect) | [\[X\]](quick_select/quick_select.c) | | | | | [Quicksort](https://en.wikipedia.org/wiki/Quicksort) | [\[X\]](quicksort/quicksort.c) | | | | diff --git a/quick_select/quick_select.c b/quick_select/quick_select.c new file mode 100644 index 00000000..ee39ee3f --- /dev/null +++ b/quick_select/quick_select.c @@ -0,0 +1,60 @@ +#include + +/* + * partition function + * ar : array on which partitioning has to be done + * left : left index of the partitioning subarray + * right : right index of the partitioning subarray + * pivot_idx : pivot index from which partition has to done + * store_idx : index of the last element of the left subarray + */ +int partition(int *ar, int left, int right, int pivot_idx) { + int pivot_value = ar[pivot_idx]; + int temp = ar[right]; + ar[right] = ar[pivot_idx]; + ar[pivot_idx] = temp; + + int store_idx = left; + while (left < right) { + if (ar[left] < pivot_value) { + temp = ar[store_idx]; + ar[store_idx] = ar[left]; + ar[left] = temp; + store_idx++; + } + left++; + } + temp = ar[right]; + ar[right] = ar[store_idx]; + ar[store_idx] = temp; + return store_idx; +} + +/* + * Quick Select function + * left : left index of the subarray + * right : right index of the subarray + * pos : position to find the element using quick sort + * pivot_index : pivot index + */ +int quick_select(int *ar, int left, int right, int pos) { + int pivot_index; + if (left == right) + return ar[left]; + pivot_index = right - 1; + pivot_index = partition(ar, left, right, pivot_index); + if (pos == pivot_index) { + return ar[pivot_index]; + } else if (pos < pivot_index) { + return quick_select(ar, left, pivot_index - 1, pos); + } else { + return quick_select(ar, pivot_index + 1, right, pos); + } +} + +int main() { + int ar[] = {10, 5, 1, 6, 7, 3, 2, 4, 8, 9}; + printf("%d\n", quick_select(ar, 0, 9, 3)); + return 0; +} +