编辑代码

#include <stdio.h>
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;

    for (int j = low; j < high; j++) {
        if (arr[j] >= pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return i + 1;
}

int findKthLargestHelper(int arr[], int low, int high, int k) {
    if (low <= high) {
        int pivotIndex = partition(arr, low, high);
        if (pivotIndex == k - 1) {
            return arr[pivotIndex];
        } else if (pivotIndex > k - 1) {
            return findKthLargestHelper(arr, low, pivotIndex - 1, k);
        } else {
            return findKthLargestHelper(arr, pivotIndex + 1, high, k);
        }
    }
    return -1; 
}

int findKthLargest(int arr[], int size, int k) {
    if (k <= 0 || k > size) {
        return -1; 
    }
    return findKthLargestHelper(arr, 0, size - 1, k);
}

int main() {
    int arr[] = {25,1,12,28,3,17,80};
    int size = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    int result = findKthLargest(arr, size, k);
    if (result != -1) {
        printf("第 %d 大的元素是: %d\n", k, result);
    } else {
        printf("无效输入数值 k\n");
    }
    return 0;
}