【问题标题】:Sorting in alphabetical order using Partition and Swap使用分区和交换按字母顺序排序
【发布时间】: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 个字符串地址的函数。传递 2 int 没有意义。当然,您的编译器必须(或应该)提供警告。发布容易发出警告的代码意味着 1) 你没有编译代码(这是一个主要的禁忌) 2) 没有启用警告(全部启用) 3) 使用古老的编译器(获得新的编译器)或 4)忽略这些警告。 (阅读它们并采取行动)。

标签: c sorting partitioning arrays alphabetical


【解决方案1】:

可以找到关于这种分区排序方法的简短说明,并附上一篇长文章的链接。 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 2021-05-18
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2023-01-30
    相关资源
    最近更新 更多