N个元素的数组中找出出现多于N/2次的数(主元素)

来源:互联网 发布:遗传算法 电子书 编辑:程序博客网 时间:2024/04/27 19:27
/*
N个元素的数组中找出出现多于N/2次的数(主元素)问题一:如何构造一个数组,此数组中有数字出现多于N/2次?随机生成一个数,将此数随机插入N/2+1次到数组中,其它空位再用随机生成数来填充问题二:如果存在多于N/2次的数,如何找到它?排序,中间的数应该是出现多于N/2次的数*/
#include "iostream"#include "ctime"#include "cstdlib"using namespace std;#define N 10int main(){int num[N] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};int index = 0; //数组下标int count  = 0; //计数int temp;srand((unsigned)time(0)); //播种子int random = rand() % N; //生成10以内的数字while(count < N/2+1) //插入N/2+1次{//生成某个范围内随机整数公式:rand() % (up - low + 1) + lowindex = rand() % N;  //随机数组下标(0~N-1)if(num[index] != random){num[index] = random; count++;}}for(int i = 0; i < N; i++)  //填充未赋值的元素{int other = rand() % N;if(num[i] == -1 && other != random)  //没有填充{num[i] = other;}}for(int i = 0;i < N; i++) //排序,输出中间位置的值即为主元素{for(int j = 0; j < i; j++){if(num[i] > num[j]){temp = num[i];num[i] = num[j];num[j] = temp;}}}cout<<"主元素:"<<num[N/2];system("pause");return 0;}

0 0
原创粉丝点击