【发布时间】:2013-03-16 17:30:30
【问题描述】:
我有一个数组包含来自输入的chars,另一个数组包含指向第一个数组中相应chars 的指针。这部分进展顺利。
然后我想对 char** 数组(指针数组)进行冒泡排序,这样原始数组保持不变,但出现问题(文本未排序)。
EDIT: Please discuss only the sorting algorithm
char tab[200];//array of chars
char** t = new char*[tabLength];
//SOMETHING
....
....
int n = tabLength;//length of tab(length of the word it contains)
//TILL HERE EVERYTHING IS FINE -----------------------------------
//bubble sorting below
do{
for(int i = 0; i < n -1; i++){
if(*t[i] > *t[i+1]){
char* x = t[i];
t[i] = t[i+1];
t[i+1] = x;
}
n--;
}
}while(n>1);
cout<<"sorted input";
for(int i = 0; i < tabLength; i++)
cout<<t[i];
cout<<endl;
cout<<"original"<<tab<<endl;
【问题讨论】:
-
每个条目是 C 字符串还是单个字符?
-
为什么要自己计算长度?为什么你甚至使用 C 风格的字符串而不是
std::string?如果您确实使用了std::string,那么您只需复制字符串,然后使用std::sort对其进行排序。 -
@NPE 我认为他正在尝试对 C 样式字符串中的字母进行排序。但他并没有实际修改数组,而是将指针重新排序到该数组中。
-
@sftrabbit 是的,完全正确。
标签: c++ pointers char bubble-sort