如何在 C++ 中对字符串进行冒泡排序?

How to do bubblesort with strings in c++?

我是 C++ 的新手,我必须使用冒泡排序使字符串按升序显示。我有一个包含各种字符串的数据文件。我将这些值存储到一个数组中。当我尝试使用课本中的冒泡排序代码时,单词会像这样排序。

如何正确实施?我可能缺少一些简单的东西。谢谢

我不确定为什么会这样,但这是我用于冒泡排序的代码。

void sortListWords(string list[], int count) {
  int temp;
  for (int i = 0; i < count - 1; i++)
    for (int j = 0; j < count - (i + 1); j++)
      if (list[j] > list[j + 1]) {
        temp = list[j];
        list[j] = list[j + 1];
        list[j + 1] = temp;
      }
   }

int main(){
  // call sorting function
  // words are loaded from data file
  sortListWords(wordListing, size);

  // print array to screen
  for(int i=0; i<size; i++)
    cout << wordListing[i];

   return 0;
}

只是对您的示例进行了最小的更改。请将它与您所拥有的进行比较,您应该会看到问题出在哪里:

#include <string>
#include <iostream>

void sortListWords(std::string list[], int count) {
  std::string temp;
  for (int i = 0; i < count - 1; i++) {
    for (int j = 0; j < count - (i + 1); j++) {
      if (list[j] > list[j + 1]) {
        temp = list[j];
        list[j] = list[j + 1];
        list[j + 1] = temp;
      }
    }
  }
}

int main(){
  const int size = 4; 
  std::string wordListing[] = {"Hello", "World", "Fred", "John" };    

  // call sorting function
  // words are loaded from data file
  sortListWords(wordListing, size);

  // print array to screen
  for(int i=0; i<size; i++) {
    std::cout << wordListing[i] << '\n';
  }
  return 0;
}

我特别做的是将 temp 的类型从 int 更改为 std::string。我还在 for 循环的主体周围添加了花括号以提高可读性。

最后,我将前两行添加到您的 main 函数(用于测试):

  const int size = 4; 
  std::string wordListing[] = {"Hello", "World", "Fred", "John" };

输出为:

Fred
Hello
John
World

将此 int temp; 更改为 string temp;