我还没有上过数据结构和算法课,我在尝试做的事情上遇到了一些麻烦。
我有 2 个大数组,第一个是 char
,包含大约 80k-100k 个单词,第二个是 int
数组,包含相同数量的整数(例如,用 words[502]
的出现次数写在 integers[502]
中)。
我必须对它们进行排序,这样最大的整数和它对应的词是第一个,第二大的第二个等等,是否可以不使用冒泡排序(这对这些数字来说太慢了)?
void bubble_sort(int n)
{
int i,j,temp;
char tempwordy[40]={0};
for(i=1;i< n;i++)
{
for(j=0;j< n-1;j++)
{
if(counters[j]>counters[j+1])
{
temp=counters[j];
counters[j]=counters[j+1];
counters[j+1]=temp;
strcpy(tempwordy,words[j]);
strcpy(words[j],words[j+1]);
strcpy(words[j+1],tempwordy);
}
}
}
}
最佳答案
使用结构
struct word
{
char word[100];
int count;
};
struct word array[502];
使用 stdlib.h
中的 qsort
函数对其进行排序。
int compare(const void* a, const void* b)
{
const struct array *ia = (const struct array *)a;
const struct array *ib = (const struct array *)b;
if(*ia.count>*ib.count)
return 1;
else if(*ia.count==*ib.count)
return 0;
else
return -1;
}
qsort(array,502,sizeof(array[0]),compare);
关于c - 排序 2 个大数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21258065/