统计数组中各个数字出现的次数
#include <iostream>
using namespace std;
void SortAge(int ages[],int length)
{
if (ages==NULL||length<=0)
return;
const int oldestage=99;
int timesages[oldestage+1]={0};
for (int i=0;i<length;i++)
{
int age=ages[i];
if(ages<0||age>oldestage)
{
cout<<"年龄输入错误"<<endl;
return;
}
++timesages[age];
}
int index=0;
for(int i=0;i<=oldestage;i++)
{
for(int j=0;j<timesages[i];j++)
{
ages[index]=i;
++index;
}
}
for (int i=1;i<=oldestage;i++)
{
if(timesages[i])
cout<<i<<":"<<timesages[i]<<endl;
}
}
void test()
{
int ages[]={12,3,42,54,4,32,12,6,3,12,12,1,23,4,5,3,2,13,4,43,2,1};
SortAge(ages,sizeof(ages)/sizeof(int));
}
把一个数组最开始的若干数字移到数组末尾,求该数组的最小数
#include <iostream>
using namespace std;
int minorder(int* num,int index1,int index2)
{
int result=num[index1];
for(int i=index1+1;i<=index2;i++)
{
if(result>num[i])
result=num[i];
}
return result;
}
int MinData(int* num,int length)
{
if(num==NULL||length<=0)
{
cout<<"数组为空"<<endl;
return 0;
}
int index1=0;
int index2=length-1;
int midindex=index1;
while (num[index1]>=num[index2])
{
if(index2-index1==1)
{
midindex=index2;
break;
}
midindex=(index1+index2)/2;
if(num[index1]==num[index2]&&num[midindex]==num[index1])
{
return minorder(num,index1,index2);
}
if(num[midindex]>=num[index1])
{
index1=midindex;
}
else if (num[midindex]<=num[index2])
{
index2=midindex;
}
}
return num[midindex];
}
void testmin()
{
int arr[]={3,4,5,1,2};
int arr1[]={4,5,6,0,1};
int arr2[]={1,0,0,0,0};
int arr3[]={1,1,1,0,1};
cout<<MinData(arr,sizeof(arr)/sizeof(int))<<endl;
cout<<MinData(arr1,sizeof(arr1)/sizeof(int))<<endl;
cout<<MinData(arr2,sizeof(arr2)/sizeof(int))<<endl;
cout<<MinData(arr3,sizeof(arr3)/sizeof(int))<<endl;
}
测试代码
#include "SortAge.h"
#include "MinData.h"
int main()
{
test();
testmin();
system("pause");
return 0;
}