如何使用快速排序对字符串数组进行排序

How to use Quick Sort to sort an array of strings

本文关键字:排序 数组 字符串 何使用 快速排序      更新时间:2023-10-16

我想使用快速排序(std::qsort(arg,arg,arg))而不是(std::sort(arg,arg,arg))来对字符串数组进行排序s[ ]
那么我还需要在以下代码中更改什么。

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main(){
    int t;
    scanf("%d",&t);
    while (t--) {
        char x[1010];
        string s[1010];
        scanf("%s", x);
        int len  = strlen(x);
        s[len] = "";
        for(int i = len - 1; i >= 0; --i) {
            s[i] = x[i];
            s[i] += s[i+1];
        }
  //  s[] now contains len number of strings 
        sort(s, s + len);      // So its here where I want to use qsort
    }
    return 0;
}

我需要传递给qsort(;;)的所有参数。如何编写用于快速排序的 cmp() 函数。

您需要创建一个比较函数来比较 2 个字符串,并将其用作 qsort 中的最后一个参数。在此处阅读有关该功能的更多信息http://www.cplusplus.com/reference/cstdlib/qsort/?kw=qsort