在c中使用qsort排序
sorting using qsort in c
我在 c
中有这段代码
const char * array[] = {
"1",
"2",
"helloworld",
"worldhello",
"3",
"zzzzzzzzzz",
"Zzzzzzzzzz",
"zzzzzzzzzZ",
};
/* n_array is the number of elements in the array. */
#define n_array sizeof(array)/sizeof(const char *)
/* Compare the strings. */
static int compare (const void * a, const void * b)
{
/* The pointers point to offsets into "array", so we need to
dereference them to get at the strings. */
return strcmp (*(const char **) a, *(const char **) b);
}
int main ()
{
int i;
qsort (array, n_array, sizeof (const char *), compare);
for (i = 0; i < 50000; i++) {
printf ("%d: %s.\n", i, array[i]);
}
return 0;
}
我希望输出变成这样
helloworld
worldhello
Zzzzzzzzzz
zzzzzzzzzz
zzzzzzzzzZ
我如何修改我的代码以获得输出
有两个错误:
a) 到 compare
中的许多解引用指针,实际上要简单得多:
static int compare (const void * a, const void * b) {
return strcmp (a, b);
}
b) 你的输出循环,要达到 50000,真的吗?
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
去掉“1”、“2”、“3”是另一个练习。
由于'Z'小于'h',所以排在第一位。
您当然可以使用 stricmp
(或 strcmpi
),但现在其中包含 Z 或 z 的字符串将按任意顺序排序。
然后是字符串“1”、“2”、“3”,你不能删除它们(实际上你可以,但不能排序)。
所以你的愿望无法实现
我在 c
中有这段代码const char * array[] = {
"1",
"2",
"helloworld",
"worldhello",
"3",
"zzzzzzzzzz",
"Zzzzzzzzzz",
"zzzzzzzzzZ",
};
/* n_array is the number of elements in the array. */
#define n_array sizeof(array)/sizeof(const char *)
/* Compare the strings. */
static int compare (const void * a, const void * b)
{
/* The pointers point to offsets into "array", so we need to
dereference them to get at the strings. */
return strcmp (*(const char **) a, *(const char **) b);
}
int main ()
{
int i;
qsort (array, n_array, sizeof (const char *), compare);
for (i = 0; i < 50000; i++) {
printf ("%d: %s.\n", i, array[i]);
}
return 0;
}
我希望输出变成这样
helloworld
worldhello
Zzzzzzzzzz
zzzzzzzzzz
zzzzzzzzzZ
我如何修改我的代码以获得输出
有两个错误:
a) 到 compare
中的许多解引用指针,实际上要简单得多:
static int compare (const void * a, const void * b) {
return strcmp (a, b);
}
b) 你的输出循环,要达到 50000,真的吗?
for (i = 0; i < n_array; i++) {
printf ("%d: %s\n", i, array[i]);
}
去掉“1”、“2”、“3”是另一个练习。
由于'Z'小于'h',所以排在第一位。
您当然可以使用 stricmp
(或 strcmpi
),但现在其中包含 Z 或 z 的字符串将按任意顺序排序。
然后是字符串“1”、“2”、“3”,你不能删除它们(实际上你可以,但不能排序)。
所以你的愿望无法实现