冒泡排序不起作用

时间:2017-12-03 19:20:33

标签: c sorting

我尝试使用冒泡排序对一组字符串进行排序,但由于某种原因它无法正常工作。它只是打印字符串。我试图解决它,但问题仍然存在。我该怎么办?我想按字母顺序对字符串进行排序

    #include<stdio.h>
    #include<string.h>

    int main(){
       int i,j,count;
       char str[20][50],temp[20];
       printf("How many strings u are going to enter?: ");
       scanf("%d",&count);

       printf("Enter Strings one by one: ");
       for(i=0;i<=count;i++)
          gets(str[i]);


       bubbleSort(str ,count);

       printf("Order of Sorted Strings:");
       for(i=0;i<=count;i++)
          puts(str[i]);

       return 0;
    }

    void bubbleSort(char *str[], int count){
 int i, j;

 for(i = 1; i < count; i++){
    for(j = 1; j < count; j++){
        if (strcmp(str[j - 1], str[j]) > 0) {
            swap(str[j], str[j-1]);
        }
    }
}


 return;
}
void swap(char *x, char *y){
    char temp[20];
  strcpy(temp, x);
  strcpy(x, y);
  strcpy(y, temp);

 return;
}

1 个答案:

答案 0 :(得分:0)

问题是str[j-1] > str[j]没有对字符串值进行比较。它正在比较字符串值的内存地址。由于所有内容都在连续内存中的数组中,因此地址str[j-1]将始终小于地址str[j],并且不会交换任何内容。

您需要使用strcmp对字符串的值进行比较。