C++:对单词而不是数字进行快速排序

C++: Quicksort words instead of numbers

本文关键字:数字 快速排序 单词 C++      更新时间:2023-10-16

我正在尝试编写一个使用快速排序按字母顺序对单词进行排序的代码,但是当我运行代码时,它卡在输入用户的单词上。这背后的原因是什么?当我将数组保留为整数数组时,它工作正常。提前感谢!

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
void quicksort(char a[], int size, int left, int right)
{
    int i = left;
    int j = right;
    int pivot = a[(left+right)/2];
    char temp;
    while (i <= j)
    {
        while (a[i] < pivot) i++;
        while (a[j] > pivot) j--;
        if (i <= j)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }
    if (i < right)
        quicksort(a, size, i, right);
    if (j > left)
        quicksort(a, size, left, j);
}
int main()
{
    char a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
    for (int i = 0; i < n; i++)
        cin >> a[i];
        quicksort(a, n, 0, n-1);
        cout << endl;
    cout << "The sorted elements are: " << endl;
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
        cout << endl;
    return 0;
}

您的代码可能有效,但您正在尝试阅读字符数组中的单词。您需要使用字符串(存储整个单词(或字符串数组(存储多个字符串(。

您的代码可能如下所示:

int main()
{
    string a[10], n;
    system("clear");
    cout << "Enter the number of elements to be sorted: " << endl;
    cin >> n;
    cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
        quicksort(a, n, 0, a[i].length -1);
    }
    cout << "The sorted elements are: " << endl;
    for (int i = 0; i < n; i++)
        cout << a[i] << " " << endl;
    return 0;
}

请记住,C ++中的代码结构与python不同。查看此编码和命名约定http://www.dofactory.com/reference/csharp-coding-standards

谢谢大家的帮助!这是最终的解决方案:

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
void quicksort(std::string a[], int size, int left, int right)
{
int i = left;
int j = right;
std::string pivot = a[(left+right)/2];
std::string temp;
while (i <= j)
{
    while (a[i] < pivot) i++;
    while (a[j] > pivot) j--;
    if (i <= j)
    {
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        i++;
        j--;
    }
}
if (i < right)
    quicksort(a, size, i, right);
if (j > left)
    quicksort(a, size, left, j);
}
int main()
{
std::string a[100];
int n;
system("clear");
cout << "Enter the number of elements to be sorted: " << endl;
cin >> n;
cout << "Enter the elements to be sorted (press ENTER after each word): " << endl;
for (int i = 0; i < n; i++)
{
    cin >> a[i];
}
quicksort(a, n, 0, n-1);
cout << endl;
cout << "The sorted elements are: " << endl;
for (int i = 0; i < n; i++)
    cout << a[i] << " ";
cout << endl;
return 0;
}