开发者

Alphabetizing (Sorting) Vector of Pointers

I have a vector of pointers which point to a set of Critic objects. Each Critic has attributes such as UserID, First Name, Last Name, etc.

I mocked up an modified quickSort in order to sort the vector of pointers by the First Name of each Critic. The function works as intended, but only for the first few instances in the vector.

void quickSortCritics(vector<Critic*> & v, int from, int to)
{
  if (from < to) 
  {
    int middle = partition(v, from, to);
    quickSortCritics(v, from, middle - 1);
    quickSortCritics(v, middle + 1, from);
  }
}

int partition(vector<Critic*> & v, int from, int to)
{
  char pivot = (v[from]->getFirstName())[0];
  int left_index = from - 1;
  int rig开发者_Python百科ht_index = to + 1;

  do
  {
    do
    {
      right_index--;
    } while ( (v[right_index]->getFirstName())[0] > pivot);
    do
    {
      left_index++;
    } while ( (v[left_index]->getFirstName())[0] < pivot);

    if (left_index < right_index)
    {
      cout << "swapping " << v[left_index]->getFirstName() << " with " << v[right_index]->getFirstName() << endl;
      swap(v[left_index], v[right_index]);
    }
  } while ( left_index < right_index );

  return right_index;
}

Any suggestions?


If its not a homework, then why don't you use std::sort providing a comparer as third argument?

bool compare_func(const Critic* c1,const Critic* c2) { /***implement it***/ }

vector<Critic*> v;
//...

std::sort(v.begin(), v.end(), compare_func);


If you still want to use your own quick sort, this is what it would look like. I assume you are using std::string.

void quickSortCritics(vector<Critic*>& v, int top, int bottom){

  if(top < bottom){
    int middle = partition(v, top, bottom);
    quickSortCritics(v, top, middle);  // sort top partition
    quickSortCritics(v, middle + 1, bottom);  //sort bottom partition
  }
}

int partition(vector<Critic*>& v, int top, int bottom){

  std::string pivot = v[top]->getFirstName();
  int left_index = top - 1;
  int right_index = bottom + 1;
  string tmp;

  do{
    do{
      right_index--;
    }while( pivot.compare(v[right_index]->getFirstName()) < 0 );

    do{
      left_index++;
    }while( pivot.compare(v[left_index]->getFirstName()) > 0);

    if (left_index < right_index)
      swap(v[left_index], v[right_index]);

  }while( left_index < right_index );

  return right_index;
}

Then you would call it like this:

quickSortCritics(your_vector, 0, your_vector.size() - 1);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜