Skip to content

[pull] master from begeekmyfriend:master #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions 0215_kth_largest_element_in_an_array/kth_elem.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@
#include <stdlib.h>


static void show(int *nums, int lo, int hi)
{
int i;
for (i = lo; i <= hi; i++) {
printf("%d ", nums[i]);
}
printf("\n");
}

static inline void swap(int *a, int *b)
{
int t = *a;
Expand Down Expand Up @@ -38,41 +47,43 @@ static void build_max_heap(int *nums, int size)
}
}

static int quick_select(int *nums, int lo, int hi, int k)
static void quick_select(int *nums, int lo, int hi, int k)
{
if (lo >= hi) {
return hi;
return;
}

int i = lo - 1;
int j = hi + 1;
int pivot = nums[lo];
int j = hi;
int pivot = nums[hi];

while (i < j) {
/* For case of large amounts of consecutive duplicate elements, we
* shall make the partition in the middle of the array as far as
* possible. If the partition is located in the head or tail, the
* performance might well be very bad for it.
*/
while (nums[++i] > pivot) {}
while (nums[--j] < pivot) {}
while (i < hi && nums[++i] > pivot) {}
while (j > lo && nums[--j] < pivot) {}
if (i < j) {
swap(&nums[i], &nums[j]);
}
}

/* invariant: i == j + 1 or i == j */
if (j >= k - 1) {
return quick_select(nums, lo, j, k);
swap(&nums[i], &nums[hi]);
if (i + 1 >= k) {
quick_select(nums, lo, i - 1, k);
} else {
return quick_select(nums, j + 1, hi, k);
quick_select(nums, i + 1, hi, k);
}
}

int findKthLargest(int* nums, int numsSize, int k)
{
#if 0
int i = quick_select(nums, 0, numsSize - 1, k);
return nums[i];
#if 1
quick_select(nums, 0, numsSize - 1, k);
return nums[k - 1];
#else
int i;

Expand Down