如何冒泡排序数组的指针到另一个数组的字符

How to bubble sort array of pointers to the another array of chars

本文关键字:数组 另一个 字符 指针 冒泡排序      更新时间:2023-10-16

我有一个数组包含输入的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;

确保打印出指针所指向的值:

for(int i = 0; i < tabLength; i++)
  cout << *t[i];

我将简单地使用标准库中已有的功能:

#include <iostream>
#include <string>
#include <algorithm>
int main()
{
    std::string original;
    std::getline(std::cin, original);
    std::cout << '|' << original << "|n";
    std::string sorted = original;
    std::sort(std::begin(sorted), std::end(sorted));
    std::cout << "Sorted  : " << sorted << 'n';
    std::cout << "Original: " << original << 'n';
}

测试运行:<>之前世界你好,你今天过得怎么样?|排序:,?Haadddeeghilllnoooooorrtuwwyy你好,世界,你今天过得怎么样?