c - 使用 C 中的 qsort 按字母顺序对单词进行排序

标签 c sorting words qsort

我必须在 IT 类(class)上编写程序:

  1. 显示 100 个随机字符并使用 qsort 函数对其进行排序
  2. 用户输入 5 个单词,使用 qsort 函数按字母顺序对这些单词进行排序

目前我有这样的东西,但效果不太好:/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <conio.h>

int compare1(const void * a, const void * b) {
return ( *(char*)a - *(char*)b );
}

int compare2(const void *a, const void *b) {
    return strncmp((const char *)a, (const char *)b, 20);
}


int main(){

 int i; 
 char words[5][20], c[27]="QWERTYUIOPASDFGHJKLZXCVBNM", t[101];
 srand(time(0));
 printf("QSORT PROGRAM\n\n");
 for (i=0;i<100;i++)
     t[i]=c[rand()%26];
 printf("Order before sorting:\n");
 for (i=0;i<100;i++)
     printf("%c", t[i]);
 qsort(t,100,sizeof(char),compare1);
 printf("\n\nOrder after sorting:\n");
 for (i=0;i<100;i++)
     printf("%c", t[i]);
 printf("\n\nEnter 5 words\n");
 for(i=0;i<5;i++)
     gets(words[i]);
 qsort(words,5,sizeof(char),compare2);
 printf("\nThe sorted order:\n");
 for(i=0;i<5;i++)
     puts(words[i]);
 printf("Press Any Key to Continue ");
 getch();
 return 0;
}

最佳答案

来自 qsort 的联机帮助页:

   void qsort(void *base, size_t nmemb, size_t size,
              int(*compar)(const void *, const void *));

The qsort() function sorts an array with nmemb elements of size size. The base argument points to the start of the array.

The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.

因此,qsort() 会调用您指定的比较函数,每次都指向两个“某物”,即保存在数组中的某物。如果需要的话,它会交换“某些东西”。

有两种明显的方法可以实现这项工作。

第一种也许是最明显(但最不有用)的方法是,您可以拥有一个二维字符数组,并且 qsort 可以将一行字符与另一行交换(在这种情况下,每个字符数组都会需要具有固定长度size,包括终止零,并且所有字符串都需要精确地彼此相邻,以便它可以索引第n字符串的开头位于偏移n * 大小处。

第二种更微妙但更有用的方法是让数组成为指向要排序的字符串的指针列表。然后 qsort 只是交换指针。

你的主要问题是你两者都没有做。像这样的行:

qsort(t,100,sizeof(char),compare1);

你说每个条目的大小是sizeof(char),即一个字符长。因此,qsort 会认为您正在对仅包含 100 个字符的数组进行排序。这是行不通的。

由于这是你的作业,我想我应该让你从这里开始做。

关于c - 使用 C 中的 qsort 按字母顺序对单词进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21205635/

相关文章:

python - 比较python中两个列表中的单词

将以太网地址转换为可读形式?

c++ - 调试信息是如何组织的,它包含什么?

PHP 扩展遍历数组

r - 按多列对数据框行进行排序(排序)

javascript - 如何正确排序整数数组

java - 集合对 Arraylist 的副本进行排序(以保持原始顺序)

c - 在另一个 char 数组中写入两个 char 数组不起作用

python程序很慢

javascript - 在 JavaScript 字符串中获取单词 #n