LadyT LadyT - 9 days ago 6
C++ Question

How to do bubblesort with strings in c++?

I am new to C++ and I have to make the strings appear in ascending order using bubblesort. I have a data file with various strings in it. I stored those values into an array. When I tried the bubblesort code from my text book, the words got sorted like this.

How can I implement this correctly? It's probably something simple that I am missing. Thanks.

enter image description here

I am not sure why this happened, but here is the code I am using for the bubblesort.

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

Answer

Just made minimal changes to your example. Please compare it with what you have and you should see, where your problem is:

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

What I did in particular, was exchanging the type of temp from int to std::string. I also added curly brackets around the bodies of your for loops to improve readability.

Finally I added the first two lines to your main function (for testing):

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

The output is:

Fred
Hello
John
World