Home > Software design >  QuickSort for vector<string>
QuickSort for vector<string>

Time:03-29

I'm new to recursion and get kind of confused by it this is my first time coding Quick Sort for a string I keep getting an error. Does anyone know where I messed up?

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

void SwapValue(string &a, string &b) 
{
   string t = a;
   a = b;
   b = t;
}

void quicksort(vector<string> &list, int first, int end)
{
  int l = first;
  int r = end;
  int pivot = ((first   end) / 2);
  while (l <= r)
  {
    while (list[l] <= (list[pivot]))
        l;
    while (list[r] >= (list[pivot]))
      --r;
    if (l <= r)
    {
      swap(list[l], list[r]);
        l;
      --r;
    }
  }
  if (first <= r)
    quicksort(list, first, r);
  if (end >= l)
    quicksort(list, l, end);
}

void print(vector <string> const &a)
{
   cout << "[ ";

   for(int i=0; i < a.size(); i  )
   {
     cout << a[i] << ' ';
   }
   cout << ']';
}

int main()
{
  vector<string> test = {"Bob", "Andrew", "Joe"};
  quicksort(test, 0, test.size()-1);
  print(test);
  return 0;
}

I thought about getting the ASCII values of the first char within the string but I would have to use a nested forloop to retrieve the character and wouldn't that make QuickSort slower?

CodePudding user response:

This statement:

while (list[l] <= (pivot))

How does that even compile? Comparing a string to an integer?

I suspect you mean:

while (list[l] <= list[pivot])

Similar treatment is also needed for the while (list[r] >= (pivot)) statement. And I don't think you want to use >= on the right side.

while (i <= r)

That won't compile either since i is not defined. I suspect you meant l, not 'i'.

  •  Tags:  
  • c
  • Related