Skip to content

Commit

Permalink
Added Quick Select [C]
Browse files Browse the repository at this point in the history
Closes #10
  • Loading branch information
yashLadha committed Mar 15, 2017
1 parent c3c661b commit 6ef556d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) | | | |


Expand Down
45 changes: 45 additions & 0 deletions quick_select/quick_select.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <stdio.h>

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;
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;
}

0 comments on commit 6ef556d

Please sign in to comment.