排序的快速排序输出,给出一个附加字符
Sorted quick sort output giving an additional character
我有这个快速排序实现来对字符进行排序。
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 字符参与排序,并且由于它比其他字符小,因此它被移动到排序数组的开头,该数组在打印时打印为空白。
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用动态分配将 char* 复制到另一个字符**
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 使用连续分隔符和空最后一个字符进行拆分
- 如何比较文件中包含的下一个字符
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何从文本文件中一次读取一个字符
- 将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
- 读取输入后,输出丢失了一个字符
- 比较最后一个字符,不区分大小写(带谓词?
- 如果一个字符,比如说"9",我减去"0",我在结果上使用 is 数字,我是真还是假
- 为什么 std::istream::gcount 返回的字符比预期的多一个字符
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 在弦乐器中删除最后一个字符