复杂度n求数组的第K大值
利用快速排序的方法进行:
#include<iostream> using namespace std; int test() { int a = 98; return a; } int quickSort(int* inputArray, const int left, const int right, int bigCount, int &result) { cout << endl; cout << "right is: " << right << endl; cout << "left is: " << left << endl; if(left > right) { cout << "return -1~~~" << endl; result = -1; return -1; } //在某一次递归中,如果传入的左右两边相等,且要找第一大的数,那么就返回该值即可 if(left == right && bigCount == 1) { int tmp = inputArray[right]; cout << "inputArray[right] is: " << tmp << endl; result = tmp; return tmp; } int maxNum = 0; int i = left; int j = right + 1;//因为下面有个j--,为了能直接用,将这里的j加1,因此输入数组最后需要填充一个数 int pivot = inputArray[left]; //这里的循环进行一次遍历,在遍历的过程中,将左边大于pivot的元素以及右边小于pivot的元素进行交换,一次遍历之后,i与j相遇,此时再将pivot与j相互交换 //那么,此时处在pivot的左边的数都是小于pivot的,pivot处在右边的数都是大于pivot的 //这时候假设左边有m个数,右边有n个数,那么pivot就是第m+1小的数,倒数第n+1大的数 //假设要求第k大的数,只需要右边的个数为k-1即可 do { do i++; while(inputArray[i] < pivot); do j--; while(inputArray[j] > pivot); if(i < j) swap(inputArray[i], inputArray[j]); } while(i < j); swap(inputArray[j], inputArray[left]); cout << endl << "================after one swap==================" << endl; for(int i = 0; i < 10; i++) { cout << inputArray[i] << " "; } cout << endl; int len = right - j + 1; cout << "j is: " << j << endl; cout << "bigCount is: " << bigCount << endl; cout << "len is: " << len << endl; if(len < bigCount)//需要在左边继续寻找 { int tmp = quickSort(inputArray ,left, j - 1, bigCount - len, result); if(tmp != -1) return tmp; } else if(len > bigCount) //需要在右边继续寻找 { int tmp = quickSort(inputArray, j + 1, right, bigCount, result); if(tmp != -1) return tmp; } else { int tmp = inputArray[j]; cout << "inputArray[j] is: " << tmp << endl; result = tmp; return tmp; } } int main() { int a[] = {8, 6, 4, 2, 0, 1, 3, 5, 7, 9, 99}; cout << endl << "================origion==================" << endl; for(int i = 0; i < 10; i++) { cout << a[i] << " "; } int rrrr = 0; int result = 0; cout<<endl; result = quickSort(a, 0, 9, 4, rrrr); cout<<endl<<endl; cout << "rrrr is " << rrrr << endl; cout << "result is " << result << endl; cout<<endl<<endl; cout << endl << "================result==================" << endl; for(int i = 0; i < 10; i++) { cout << a[i] << " "; } return 0; }