【问题标题】:Bubble Sort in C array swappingC数组交换中的冒泡排序
【发布时间】:2015-04-10 04:25:00
【问题描述】:

我最近在处理这段代码的交换部分时遇到了这个问题,所以这段代码所做的是输入一个数组并使用冒泡排序方法对其进行排序。读取它的文本文件有 10 个数字和名称。像这样:

约翰 1
马克 2
马太福音 2
路加福音 3
伊萨克 4
凯恩 5
瑞恩 7
亚伯 2
亚当 9
前夕 10

但是当它打印出来时,它会显示:

约翰 1
马克 2
马太福音 2
亚伯 2
亚伯 3
亚伯 4
亚伯 5
亚伯 7
亚当 9
前夕 10
抱歉,问题是为什么它会重复 Abel,我该怎么做才能解决它?

    void bubbleSort (Word q){
    int last = 9;
    int Swapped = 1; 
    int i = 0;
    int m = 0;
    char* temp = "Hello";
    printf("Temp is: %s \n", temp);
    int tempA;
    while (Swapped == 1){
        Swapped = 0;
        i = 1;
        while (i < last){
            printf("%d \n", i);
            if (q.data[i] > q.data[i+1]) {
                printf("Hello: %d \n", i);
                //Copy Name of Element
                temp = q.name[i];
                strcpy(q.name[i], q.name[i+1]);
                strcpy(q.name[i+1] , temp);

                //Copy Data of corresponding element
                tempA = q.data[i];
                q.data[i] = q.data[i+1];
                q.data[i+1] = tempA;
                Swapped = 1; 

            } 
            i = i + 1;
        }
        last = last - 1;
    }
    last = 9;
    while (m <= last){
        printf("Name: %s, Data: %d \n", q.name[m], q.data[m]);
        m++;
    }
}

【问题讨论】:

  • 您正在根据结构的data 成员进行排序。因此,您的输出将根据该成员进行排序。你有什么问题?
  • @askmish:输出中似乎缺少 Luke 3,但我同意这个问题不是很清楚。

标签: c sorting


【解决方案1】:

而不是这个:

char* temp = "Hello";

你应该这样做:

char *temp = malloc(MAX_NAME_LEN*sizeof(char));
//check if allocation of memory was successful or handle exceptions

或者,这个:

char temp[MAX_NAME_LEN];

然后

strcpy(temp, "Hello");

您需要将字符串存储到一个临时变量中,指向实际内存,以便在字符串交换操作中使用它,在代码的后面部分。

而不是这个:

   //Copy Name of Element
   temp = q.name[i];//HERE you are storing a pointer to the address, not the actual string. Both q.name[i] and temp point to the same memory
   strcpy(q.name[i], q.name[i+1]);//Both q.name[i] and the temp pointer, with the string at q.name[i+1]. the original string in q.name[i] is lost.
   strcpy(q.name[i+1] , temp);//You are copying the same content as in q.name[i+1]. You are not copying the original content of q.name[i]

这样做:

//Copy Name of Element
strcpy(temp, q.name[i]);//HERE you are storing the actual string
strcpy(q.name[i], q.name[i+1]);//q.name[i] and temp contain distinct strings
strcpy(q.name[i+1], temp);//HERE you are copying the orginal string of q.name[i]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2012-07-05
    • 2015-01-27
    • 1970-01-01
    • 2015-07-05
    • 2015-05-27
    • 2012-02-17
    相关资源
    最近更新 更多