//1,2,3,2,2,2,5,4,2 len=9 return 2;出现次数超过一半
//元素在数组中出现的次数STL
//各种排序
void BubleSort(int num[],int len)
{
int i, j,temp;
for (i = 0; i < len; i++)
{
for (j = 0; j < len -1- i; j++)
{
if (num[j]>num[j + 1])
{
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
}
int partition(int num[], int first, int end)
{
int i, j,temp;
i = first;
j = end;
temp = num[i];
while (i < j)
{
while (i<j && num[j]>temp)
{
j--;
}
if (i < j)
{
num[i++] = num[j];
}
while (i < j && num[i] < temp)
{
i++;
}
if (i < j)
{
num[j--] = num[i];
}
}
num[i] = temp;
return i;
}
void QuickSort(int num[],int first,int end)
{
int index;
if (first < end)
{
index = partition(num, first, end);
QuickSort(num, first, index - 1);
QuickSort(num, index + 1, end);
}
}
bool istrue(int num[],int len, int index)
{
int times, i;
times = 0;
for (i = 0; i < len; i++)
{
if (num[i] == index)
{
times++;
}
}
if (times * 2 <= len)
return false;
else
return true;
}
//Find the num which was more than the half in the array
void MoreThanHalf(int num[], int len,int first,int end)//利用partition函数找到中位数
{
if (num == NULL || len < 0)
return;
int middle = len >> 1;
int index;
index = partition(num, first, end);
while (index != middle)
{
if (index < middle)
{
first = index + 1;
index = partition(num, first, end);
}
else
{
end = index - 1;
index = partition(num, first,end);
}
}
int result;
result = num[index];
if (istrue(num, len, result))
{
cout<< result;
}
else
{
cout << "Donot have!" << endl;
}
}
/*<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">数组中有个数字出现的次数超过了数组长度的一半。也就是说,有个数字出现的次数比其他所有数字出现次数的和还要多。</span><br style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;" /><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"> 因此我们可以考虑在遍历数组的时候保存两个值:一个是数组中的一个数字,一个是次数。当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1。 如果下一个数字和我们之前保存的数字不同,则次数减1。如果次数为零,我们需要保存下一个数字,并把次数重新设为1。 */</span>
int FindHalf(int *a, int n)
{
int candidate;
int times, i;
for (i = times = 0; i < n; i++)
{
if (times == 0)
{
candidate = a[i];
times = 1;
}
else
{
if (candidate == a[i])
{
times++;
}
else
{
times--;
}
}
}
return candidate;
}