c - 排序 2 个大数组

标签 c arrays algorithm sorting qsort

我还没有上过数据结构和算法课,我在尝试做的事情上遇到了一些麻烦。

我有 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/

相关文章:

c++ - 使用一维数组打印二维数组

c - 用于在二叉树中查找(有序)节点后继的代码中的段错误

c - 在c中打印armstrong no从100到10000

python - 按月将日期数组拆分为多个列表

algorithm - 幂集中的动态规划

c - STM32F103C8/CoIDE/ST-LinkV2 无法更新寄存器

javascript - 如何在 JavaScript 中创建对象/数组?

arrays - 删除 VBA 数组的第一个元素

algorithm - 将整数映射到给定字符串空间中的字符串

java - 找出将 n 表示为两个有边界整数之和的方法的数量