C++:对单词而不是数字进行快速排序
C++: Quicksort words instead of numbers
我正在尝试编写一个使用快速排序按字母顺序对单词进行排序的代码,但是当我运行代码时,它卡在输入用户的单词上。这背后的原因是什么?当我将数组保留为整数数组时,它工作正常。提前感谢!
#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;
}
相关文章:
- 如何修复我的快速排序实现?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 在 MIPS 中快速排序
- 不正确的比较和交换计数器输出用于快速排序功能
- 使用 std::vector C++快速排序,EXC_BAD_ACCESS代码 2
- 使用快速排序对 C++ 中的可视化工具错误进行排序
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 并行快速排序分区中的隔离错误
- 实现 3 路分区以实现快速排序
- 为什么这个快速排序实现给出了一个奇怪的输出
- 我的快速排序在对预排序的项目进行排序时失败,如何改进?
- 我怎么不能按课程代码的降序对数字进行排序
- 快速排序不适用于大型数组
- 快速排序;分段错误,但找不到位置?
- 快速排序函数在快速排序算法中如何工作?
- 3路随机快速排序分区功能
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 我想要一个改变数组快速排序的2个数字的函数
- C++:对单词而不是数字进行快速排序
- 快速排序不排序高范围的数字