排序的快速排序输出,给出一个附加字符

Sorted quick sort output giving an additional character

本文关键字:一个 字符 快速排序 输出 排序      更新时间:2023-10-16

我有这个快速排序实现来对字符进行排序。

int main(){
char val[] = "dcbeaaae";
    QuickSort(val, 0, length);
    for(int i=0;i<length;i++) //Sorted print
        cout<<val[i];
return 0
}
void QuickSort(char values[], int first, int last)
{
    if(first<last)
    {
        int splitPoint;
        Split(values, first, last, splitPoint);
        QuickSort(values, first, splitPoint-1);
        QuickSort(values, splitPoint+1, last);
    }
}
void Split(char values[], int first, int last, int& splitPoint)
{
    int splitVal = values[first];
    int saveFirst = first;
    bool onCorrectSide;
    first++;
    do
    {
        onCorrectSide = true;
        while(onCorrectSide)
        {
            if(values[first] > splitVal)
                onCorrectSide = false;
            else
            {
                first++;
                onCorrectSide = (first<=last);
            }
        }
        onCorrectSide = (first<=last);
        while(onCorrectSide)
            if(values[last] <= splitVal)
                onCorrectSide = false;
            else
            {
                last--;
                onCorrectSide = (first<=last);
            }
        if(first<last)
        {
            Swap(values[first], values[last]);
            first++;
            last--;
        }
    }while(first<=last);
    splitPoint = last;
    Swap(values[saveFirst], values[splitPoint]);
}
void Swap(char& item1, char& item2)
{
    char temp = item1;
    item1 = item2;
    item2 = temp;
}

但是,我从中得到的输出有点错误,即我在这些排序字符的开头获得了一个额外的空格。在放置断点时,我看到在索引 0 处,元素 = 0

输入:aaabcdee
输出:aaabcdee(在第一个 a 之前增加一个空格)

有什么建议我在这里错过了什么吗?

假设length是字符数组中的字符数(不包括 NUL 字符)。您需要调用快速排序函数,如下所示:

QuickSort(val, 0, length-1);

因为函数 QuickSort 的最后一个参数是数组最后一个元素的索引,并且在长度length的字符数组中,此索引是length - 1

通过将length传递给函数,您甚至使 NUL 字符参与排序,并且由于它比其他字符小,因此它被移动到排序数组的开头,该数组在打印时打印为空白。

相关文章: