思想,利用快排思想,不斷尋找分解點,將分界點的下標與K-1比較若是相等,返回該值,不然更新左右邊界。當左右邊界中的值少於等於2個時,運用插入排序,返回a[k-1]blog
int findCut(vector<int>& a, int l, int r) { if (l + 1 >= r) { return -1; } int pivot = a[l]; int i = l, j = r; while (true) { do { i++; } while (i<r&&a[i] < pivot); do { j--; } while (j>l&&a[j] >= pivot); if (i >= j)break; int temp = a[i]; a[i] = a[j]; a[j] = temp; } a[l] = a[j]; a[j] = pivot; return j; } void insert_sort(vector<int>&a, int l, int r) { for (int i = l + 1; i < r; i++) { int j=i,pivot = a[i]; while (j>l&&pivot < a[j-1]) { a[j] = a[j - 1]; j--; } a[j] = pivot; } } int findKth(vector<int>a, int n, int K) { int left = 0, right = n; while (left+1 < right) { int cut = findCut(a, left, right); if (cut == K - 1)return a[cut]; else if (cut < K - 1) { left = cut + 1; } else { right = cut; } } insert_sort(a, left, right); return a[K-1]; }