From fb05e13a79450eba4c8f960ec72db339d47025cd 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 | 46 +++++++++++++++++++++++++++++++++++++ 2 files changed, 47 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..5e7cd8a2 --- /dev/null +++ b/quick_select/quick_select.c @@ -0,0 +1,46 @@ +#include +#include + +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; +} + +int quick_select(int *ar, int left, int right, int pos) { + int pivot_index = 0; + 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); + } + return 0; +} + +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; +}