簡體   English   中英

向量的快速排序<string></string>

[英]QuickSort for vector<string>

我是遞歸的新手,對此感到有點困惑這是我第一次為字符串編寫快速排序代碼,但我一直收到錯誤消息。 有誰知道我在哪里搞砸了?

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

我考慮過獲取字符串中第一個字符的 ASCII 值,但我必須使用嵌套的 forloop 來檢索字符,這不會使 QuickSort 變慢嗎?

這個說法:

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

那甚至如何編譯? 將字符串與 integer 進行比較?

我懷疑你的意思是:

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

while (list[r] >= (pivot))語句也需要類似的處理。 而且我認為您不想在右側使用>=

while (i <= r)

這也不會編譯,因為i沒有定義。 我懷疑你的意思是l ,而不是“我”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM