【发布时间】:2014-10-12 23:22:39
【问题描述】:
所以我的程序使用分区排序将 10 个用户输入的姓名按字母顺序重新打印。我以前从未使用过分区排序,所以在解决这个问题时我完全没有经验。
我正在使用数字分区排序的示例,并尝试使用 strcmp 对其进行操作以进行排序。
我下面的大部分代码都是我的所有代码,但分区函数除外,这是我遇到问题的地方。有人可以帮我理解这种排序是如何工作的,以及我如何操作它以按字母顺序对 10 个名称进行排序?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define DEBUG_LEVEL 0
int partition(int a[], int left, int right);
void swap(int *a, int *b);
#define SIZE 10
int main(int argc, const char * argv[]) {
char Names[10][10];
int count = 10;
int i;
int a[SIZE];
printf("Enter 10 names:");
for (i=0; i < count; ++i)
{
gets(Names[i]);
}
printf("\n\n");
partition(a, 0, SIZE -1);
printf("The names in alphabetical order are\n");
for (i=0; i< count; ++i)
{
printf("%s\n",Names[i]);
}
getchar();
}
int partition(int a[], int left, int right) {
int i, j, key;
key = a[left];
i = left + 1;
j = right;
while (strcmp(i, j) <0) {
while (i <= right && a[i] <= key)
++i;
while (j >= left && a[j] > key)
--j;
if (i < j)
swap(&a[i], &a[j]);
}
swap(&a[left], &a[j]);
return j;
}
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
【问题讨论】:
-
1) 代码调用
partition(a, 0, SIZE -1);时,a的内容没有被初始化。 2)i, j,` 是int。打电话给strcmp((i,j)没有意义。 -
是的,就像我说的那样,我所做的就是复制这个分区段,然后将它添加到我的代码中,希望我可以操纵它来对单词进行排序。使用快速排序而不是分区排序会更容易吗?我很欣赏你的提示,但我仍然迷失了,好像这是我第一次被介绍通过任何方法进行排序@chux
-
这不是介绍排序的问题。
strcmp()是一个接受 2 个字符串地址的函数。传递 2int没有意义。当然,您的编译器必须(或应该)提供警告。发布容易发出警告的代码意味着 1) 你没有编译代码(这是一个主要的禁忌) 2) 没有启用警告(全部启用) 3) 使用古老的编译器(获得新的编译器)或 4)忽略这些警告。 (阅读它们并采取行动)。
标签: c sorting partitioning arrays alphabetical