简体   繁体   English

向量C ++按字母顺序排列的快速排序

[英]Alphabetical quicksort of Vector C++

For the following code I've been trying to implement Quicksort to Alphabetically Sort a Vector of strings. 对于以下代码,我一直在尝试实现Quicksort以按字母顺序对字符串向量进行排序。

The issue I have found is that you cannot compare strings as ">" or "<". 我发现的问题是您无法将字符串比较为“>”或“ <”。 I've also attempted using the .compare function for strings. 我也尝试对字符串使用.compare函数。

Any Advice? 有什么建议吗?

`void quicksort(vector<string> arr, int left, int right)
 {
  int i = left, j = right;
  string tmp;
  string pivot = arr[(left + right) / 2];

  /* partition */
  while (i <= j) {
        while (arr[i] < pivot)
              i++;
        while (arr[j] > pivot)
              j--;
        if (i <= j) {
              tmp = arr[i];
              arr[i] = arr[j];
              arr[j] = tmp;
              i++;
              j--;
    }
}
/* recursion */
if (left < j)
    quickSort(arr, left, j);
if (i < right)
        quickSort(arr, i, right);
}`

I Will also Later be attempting MergeSort, and InsertSort 我稍后还将尝试MergeSort和InsertSort

The issue I have found is that you cannot compare strings as ">" or "<". 我发现的问题是您无法将字符串比较为“>”或“ <”。

False. 假。 std::string provides overloaded < and > that you can use for comparison. std::string提供了可用于比较的重载<>

The problem you're having is that you're passing the arr argument by value. 您遇到的问题是您arr值传递arr参数。 You should pass it by reference to be able to modify the original vector you passed to quicksort : 您应该通过引用传递它,以便能够修改传递给quicksort的原始vector

void quicksort(vector<string>& arr, int left, int right)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM