查找数组中的前M大的数
- 思路
根据快速排序的Partition的思想,假定数组长度为n, 选定一个pivot,总能将数组分为 [0,k-1]和[k,n],
其中[0,k-1]<pivot,[k+1,n] > pivot。如果 k = m, 那么算法结束。如果k > m, 对[k+1,n]继续进行切分,
每次切分k都会减少一部分, 直到k = m, 如果k < m, 对[0,k-1]继续切分出m-k个大的数, 每次切分k都会
增加一部分,直到k = m。
- 算法复杂度
平均算法复杂度为:O(n) = n,最坏情况的复杂度为:O(n) = n。
cpp实现
int Partition(int arr[], int start, int end) {
int pivot = arr[start];
int highvac = end;
int lowvac = start;
int direct = true; //true for right,false for left. start from left
while(lowvac < highvac) {
if(direct == true) {
if(arr[highvac] <pivot) {
arr[lowvac] = arr[highvac];
lowvac++;
direct = false;
} else {
highvac--;
}
} else {
if(arr[lowvac] > pivot) {
arr[highvac] = arr[lowvac];
highvac--;
direct = true;
} else {
lowvac++;
}
}
}
arr[highvac] = pivot;
return highvac;
}
int* findXMaxValue(int arr[], int xmax, int start, int end) {
int p = 0;
static int* maxs = new int[xmax];
int cmax = end - start +1;
int len = end;
if (xmax >= len+1) {
return arr;
}
while(cmax != xmax) {
p = Partition(arr,start,end);
cmax = len-p+1;
if(cmax > xmax) {
start = p+1;
} else if ( cmax < xmax) {
end = p-1;
start = 0;
}
}
for(int j = 0; j < xmax; j++) {
maxs[j] = arr[p+j];
}
return maxs;
}