题目:
题解:
static inline void swap(int *a, int *b) {
int c = *a;
*a = *b;
*b = c;
}
static inline int partitionAroundPivot(int left, int right, int pivot, int *nums) {
int pivotValue = nums[pivot];
int newPivot = left;
swap(&nums[pivot], &nums[right]);
for (int i = left; i < right; ++i) {
if (nums[i] > pivotValue) {
swap(&nums[i], &nums[newPivot++]);
}
}
swap(&nums[right], &nums[newPivot]);
return newPivot;
}
static int findKthLargest(int* nums, int numsSize, int k) {
int left = 0, right = numsSize - 1;
srand(time(0));
while (left <= right) {
int pivot = rand() % (right - left + 1) + left;
int newPivot = partitionAroundPivot(left, right, pivot, nums);
if (newPivot == k - 1) {
return nums[newPivot];
} else if (newPivot > k - 1) {
right = newPivot - 1;
} else {
left = newPivot + 1;
}
}
return nums[k - 1];
}
static inline int transAddress(int i, int n) {
return (2 * n - 2 * i - 1) % (n | 1);
}
void wiggleSort(int* nums, int numsSize) {
int x = (numsSize + 1) / 2;
int mid = x - 1;
int target = findKthLargest(nums, numsSize, numsSize - mid);
for (int k = 0, i = 0, j = numsSize - 1; k <= j; k++) {
if (nums[transAddress(k, numsSize)] > target) {
while (j > k && nums[transAddress(j, numsSize)] > target) {
j--;
}
swap(&nums[transAddress(k, numsSize)], &nums[transAddress(j--, numsSize)]);
}
if (nums[transAddress(k, numsSize)] < target) {
swap(&nums[transAddress(k, numsSize)], &nums[transAddress(i++, numsSize)]);
}
}
}