简体   繁体   English

使用快速排序在 C 中对字符串进行排序

[英]Sort a string in C with quick sort

I want to sort a string in C according to the ASCII value of each char in the string.我想根据字符串中每个字符的 ASCII 值对 C 中的字符串进行排序。 I write a quick sort to do this.我写了一个快速排序来做到这一点。 My code is as following:我的代码如下:

#include<stdio.h>
#include<stdlib.h>
void quick_sort(char* str, int l, int r) {
    if (l < r) {
        int left = l;
        int right = r;
        char x = *str;

        while (left < right) {
            while (left < right && *(str+right) > x)
                right--;
            if (left < right)
                *(str+(left++)) = *(str+right);
            while (left < right && *(str+left) < x)
                left++;
            if (left < right)
                *(str+(right--)) = *(str+left);
        }

        *(str+left) = x;
        quick_sort(str, l, left-1);
        quick_sort(str, right+1, r);    
    }
}

main() {
    char* str = (char*)malloc(sizeof(char)*100);

    printf("please input a string: ");
    scanf("%s", str);
    printf("the original string is: %s\n", str);
    quick_sort(str, 0, strlen(str)-1);
    printf("the sorted string is: %s\n",str);

    free(str); 
    system("pause");
}

But it can only work when the string is very short, say "bac".但它只能在字符串很短的时候工作,比如“bac”。 When the string is longer, the result is wrong.当字符串较长时,结果是错误的。 It would be helpful if anyone could give me any ideas.如果有人能给我任何想法,那将会很有帮助。

Your partition algorithm is lossy.您的分区算法有损。

When the condition is true, the following:当条件为真时,如下:

        if(left < right)
            *(str+(left++)) = *(str+right);

overwrites str[left] .覆盖str[left] Once this happens, the character is irreversibly lost.一旦发生这种情况,角色将不可逆转地丢失。

The same goes for the other if .另一个if也是if

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM