找出数组中第K大的数值

来源:互联网 发布:泰民kai知乎 编辑:程序博客网 时间:2024/05/22 04:57

使用快速选择算法 quickSelect

pivot为随机取法

#include <stdio.h>#include <stdlib.h>void swap(int& a, int& b){int tmp = a;a = b;b = tmp;};int partition(int* arr, int l, int r){int random = rand() % (r - l + 1);int pivotIdx = l + random;swap(arr[pivotIdx], arr[r]);int pivot = arr[r];int front = l;for(int i = l; i < r; i++){if(arr[i] < pivot){swap(arr[i], arr[front]);front++;}}swap(arr[front], arr[r]);return front;};int quickSelect(int* arr, int k, int l, int r){if(l < r){int pivot = partition(arr, l, r);if(pivot == k - 1)return arr[pivot];else if(pivot < k - 1)return quickSelect(arr, k, pivot + 1, r);else return quickSelect(arr, k, l, pivot - 1);}};int main(){srand(10);int a[] = {5, 1, 2, 3, 4, 7, 6};int res = quickSelect(a, 7, 0, 6);return 0;}


原创粉丝点击