题目:
我的代码:
void sort_maoPao(int* people,int peopleSize)
{
int i,j;
int temp = 0;
for(i=0;i<peopleSize-1;i++){
for(j=1;j<peopleSize-i;j++){
if(people[j-1]<people[j]){
temp = people[j];
people[j] = people[j-1];
people[j-1] = temp;
}
}
}
}
void sort_jiShu(int* const people,int peopleSize,int min,int max)
{
int i,j;
int* num;
num = (int*)malloc(max*4+4);
memset(num,0,sizeof(int)*(max+1));
//将数组people中min~max的数字的个数分别存放在num数组的,num数组的下标对应当前存的数字
for(i=min;i<=max;i++){
for(j=0;j<peopleSize;j++){
if(people[j] == i){
num[i]++;
}
}
}
/*
for(i=min;i<=max;i++){
printf("num[%d]:%d\n",i,num[i]);
}
*/
//按照num中各个数字的个数,对people重新赋值
int n = 0;
for(i=max;i>=min;i--){
for(j=0;j<num[i];j++){
people[n] = i;
n++;
}
}
}
void peopleMinAndMax(int* people,int peopleSize,int* const min,int* const max)
{
int i;
for(i=0;i<peopleSize;i++){
if(*min>people[i]){
*min = people[i];
}
if(*max<people[i]){
*max = people[i];
}
}
}
int numRescueBoats(int* people, int peopleSize, int limit){
int left = 0;
int ret = peopleSize-1;
int num = 0;
int min = people[0];
int max = people[0];
peopleMinAndMax(people,peopleSize,&min,&max);
//printf("min:%d\nmax:%d\n",min,max);
//sort_maoPao(people,peopleSize);
sort_jiShu(people,peopleSize,min,max);
/*
for(int i=0;i<peopleSize;i++){
printf("%d ",people[i]);
}
*/
for(left=0;left<=ret;left++){
if(people[left] == limit){
num++;
continue;
}
if( (people[left]+people[ret]) <= limit){
num++;
ret--;
continue;
}else{
num++;
continue;
}
if(left == ret){
num++;
}
}
return num;
}
问题:
一开始我用的冒泡排序,但是有一组测试案例给的数据量特别大,5000多个,用冒泡排序会超时;
后来我发现这组数据最小值到最大值跨度不是很大,我就用了计数排序;
结果在这个案例后面还有一个案例:数据量大,最小值到最大值跨度也大0.0;
然后冒泡和计数排序都会超时;
请问有没有更好的排序算法,或者解决方法