所以我的程序正在使用分区排序将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;
}
答案 0 :(得分:0)
可以找到这种分区排序方法的简短说明,其中包含指向长篇文章的链接。 G。在维基百科上:Quicksort。
由于chux声明的原因,所显示的代码无法工作,而且因为缺少递归调用子分区。这是一个工作版本:
void swap(char a[10], char b[10])
{
char temp[10];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
}
void partition(char Names[][10], int left, int right)
{
int i, j;
char *key;
if (right <= left) return;
key = Names[left];
i = left+1;
j = right;
for (; ; )
{
while (i <= right && strcmp(Names[i], key) <= 0) ++i;
while (j >= left && strcmp(Names[j], key) > 0) --j;
if (i < j) swap(Names[i], Names[j]);
else { swap( key, Names[j]); break; }
}
partition(Names, left, j-1);
partition(Names, i, right);
}