-
Notifications
You must be signed in to change notification settings - Fork 497
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Closes #10
- Loading branch information
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|