算法:分治法寻找众数

注意:快速排序之后相同的数组元素是相邻的。

#include

using namespace std;


void Quick_Sort(int *a,int begin,int end){
    
 if(begin>end)
  return;
    int tmp = a[begin];
    int i = begin;
    int j = end;
    while(i!=j){
     while(a[j]>=tmp&&j>i)
   j--;
  while(a[i]<=tmp&&j>i)
   i++;

  if(i<j){
   int t = a[i];
   a[i] = a[j];
   a[j] = t;
 }

}
  a[begin] = a[i];
     a[i] = tmp;

  Quick_Sort(a,begin,i-1);
     Quick_Sort(a,i+1,end);
}


int count_num(int *a,int length){
    int count = 0;
 int max_count = 0;
 int chose_num;
    int i = 0;
 int j = 0;
    while(i<length){
  j = i+1;
  while(a[i]==a[j]&&i<length){
   i++;
   count++;
   cout<<count<<endl;
  }
  if(count>max_count)
  {
     max_count = count;
           chose_num = a[j];
     count = 0;
  }
  i++;
 }

 cout<<"众数是:"<<chose_num<<endl;
 cout<<"众数的个数:"<<max_count<<endl;
 return 0;
}

int main(){
 int a[10] = {1,2,3,4,5,6,7,8,9,9};
    Quick_Sort(a,0,9);
    count_num(a,10);
    return 0;
}

你可能感兴趣的:(算法,快速排序,数组,众数,C++,算法)