C ++:Quicksort单词而不是数字

时间:2017-04-02 08:36:51

标签: c++ quicksort

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

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

}

2 个答案:

答案 0 :(得分:0)

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

您的代码可能如下所示:

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

答案 1 :(得分:0)

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

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

}
相关问题