#include <iostream>
#include <time.h> //use time(NULL) in line8
#include <stdlib.h> //use srand() in line8
using namespace std;
//*****************************************************
//used by partition,get rand number in [start,end]
int RandomInRange(int start,int end){
srand(time(NULL));
return start+rand()%(end-start+1);
}
//used by partition,swap a and b
void swap(int *a,int *b){
int tmp=*a;
*a=*b;
*b=tmp;
}
//famous function partition!
int partition(int *number,int length,int start,int end){
//!!!!!!!!!!!!!!to be handle:how to use exception
//if(number==NULL||length<=0||start<0||end>length-1)
//throw new std::exception("Invalid Input.");
int index=RandomInRange(start,end);
swap(&number[end],&number[index]);
int smallnext=start;
for(int i=start;i<end;++i){
if(number[i]<number[end] ){
if(i!=smallnext)
swap(&number[i],&number[smallnext]);
++smallnext;
}
}
swap(&number[smallnext],&number[end]);
return smallnext;
}
//******************************************************
//solution 1:using partition and narrow to length/2
int MoreThanHalf(int *number,int length){
if(number==NULL||length<=0)
return 0;
//get index==length/2 by using partition
int start=0,end=length-1;
int index=partition(number,length,start,end);
while(index!=(length>>1)){
if(index<(length>>1)){
start=index+1;
index=partition(number,length,start,end);
}
else{
end=index-1;
index=partition(number,length,start,end);
}
}
//check if result really appear more than half
int count=0;
for(int i=0;i<length;++i){
if(number[i]==number[index])
count++;
}
if(count*2<=length)
return 0;
//return result
return number[index];
}
//solution2:get a number and count(not change the initial array)
int MoreThanHalf2(int *number,int length){
if(number==NULL||length<=0)
return 0;
int result=*number;
int count=1;
for(int i=1;i<length;++i){
if(count==0){
result=number[i];
count=1;
}
else if(number[i]==result)
++count;
else
--count;
}
//check if result really appear more than half
int count2=0;
for(int i=0;i<length;++i){
if(number[i]==result)
count2++;
}
if(count2*2<=length)
return 0;
return result;
}
int main(){
int array[11]={5,2,4,2,5,2,5,2,2,3,2};
cout<<MoreThanHalf(array,sizeof(array)/sizeof(array[0]));
cout<<MoreThanHalf2(array,sizeof(array)/sizeof(array[0]));
}