# include <iostream>
# include <vector>
using namespace std;
//快速排序算法
int Partition(vector<int>* a, int begin, int end){
int i = begin;
int j = end;
int key = (*a)[begin];
while(i<j){
while(i<j && key <= (*a)[j]){
j--;
}
(*a)[i] = (*a)[j];
while(i<j && key >= (*a)[i]){
i++;
}
(*a)[j] = (*a)[i];
}
(*a)[i] = key;
return i;
}
void find_the_small_values(vector<int>* a,int k, vector<int>* result){
if(a==NULL){
return;
}
else{
int first = 0;
int last = int(a->size()-1);
//利用快排,index前面的元素小,index后面的元素大
int index = Partition(a,first,last);
while(index!=k){
//index前面的元素个数小于k个
if(index<k){
//继续往后找
first = index + 1;
index = Partition(a,first,last);
}
//index前面的元素个数大于k个
else{
//继续往前查找
last = index - 1;
index = Partition(a,first,last);
}
}
//取k位置前面的k个小元素作为输出
if(index == k){
for(int i = 0;i<k;i++){
result->push_back((*a)[i]);
}
}
}
}
int find_the_half_values(vector<int>* a){
if(a==NULL){
return 0;
}
else{
int first = 0;
int last = int(a->size()-1);
int index = Partition(a,first,last);
int mid = last >> 1;
//和上面函数原理一样,不过这里为了找到数组的中位数
while(index!=mid){
if(index<mid){
first = index + 1;
index = Partition(a,first,last);
}
else{
last = index - 1;
index = Partition(a,first,last);
}
}
int count = 0;
//判断中位数的个数是否满足要求
if(index == mid){
for(auto i = a->begin();i!=a->end();i++){
if((*a)[index] == *i){
count++;
}
}
}
if(2*count>int(a->size())){
return (*a)[mid];
}
else{
return 0;
}
}
}
int main(){
vector<int>* a = new vector<int>;
vector<int>* result = new vector<int>;
*a = {1,2,1,2,1,1,5};
find_the_small_values(a,3,result);
for(auto i = result->begin();i!=result->end();i++){
cout << *i << "->";
}
cout << endl;
int count = find_the_half_values(a);
cout << "the half value" << count;
return 0;
}