I am trying to write a code that uses quicksort to sort words by alphabetical order, but when I run my code it gets stuck on inputting the user's words. What's the reason behind this? It works fine when I leave the array as an integer array. Thanks in advance!
#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;
}
a
is an array of characters, socin >> a[i]
reads a single character. But later, in the sort you do sort the characters again, not whole strings/words. I would suggest usingstd::string
for the sake of simplicity. – CygnusX1 Apr 2 '17 at 8:41string
in order for it to sort words? Sorry, I'm fairly new to C++. @CygnusX1 – Patricia Wang Apr 2 '17 at 8:46