【问题标题】:How to bubble sort array of pointers to the another array of chars如何对指向另一个字符数组的指针数组进行冒泡排序
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢。你能看看我切断代码的编辑,所以只有排序算法可见。我只想对 t 数组(排序指针)进行排序。
【解决方案2】:

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

#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';
}

试运行:

|你好世界,你今天好吗?| 已排序 : ,?Haadddeeghillllnoooooorrtuwyy 原文:Hello World,你今天好吗?

【讨论】:

  • 因为我试图了解如何对指向其他数组元素(字符而不是字符串)的指针数组进行排序。
猜你喜欢
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
  • 2014-03-11
相关资源
最近更新 更多