arihanian - 1 year ago 93
C Question

# Get a series of lower case letters sorted

The algorithm works fine with integers but since I converted them into char, it has been printing null for the output:

``````/* sort a series of lower case letters using quicksort algorithm. */
#include <stdio.h>

#define N 10

// since c gets the ascii code when returning an int for a char variable.

char quicksort(char a[], char low, char high);
char split(char a[], char low, char high);
int a[N];

int main(void)
{
int i;

printf("Enter  letters to be sorted: ");
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
quicksort(a, 0, N - 1);

printf("In sorted order: ");
for (i = 0; i < N; i++)
printf("%s ", a[i]);
printf("\n");

return 0;
}
char quicksort(char a[], char low, char high)
{
int middle;

if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
char split(char a[], char low, char high)
{
char part_element = a[low];

for (;;) {
while (low < high && part_element <= a[high])
high--;
if (low >= high) break;
a[low++] = a[high];

while (low < high && a[low] <= part_element)
low++;
if (low >= high) break;
a[high--] = a[low];
}

a[high] = part_element;
return high;
}
``````

The revised code still doesnt work and i cant seem to find the bug.

Your problems appear to be with `main()` pretty much along the lines that other folks have suggested with respect to using `char` oriented data instead of `int`. There are some non fatal questionable choice issues like using `char` datatypes for array indexes; `quicksort()` is declared to return `char` but returns nothing; and so forth. Below is a rework of your code, mostly for style, incorporating various folks suggestions:

``````/* sort a series of letters using quicksort algorithm. */

#include <stdio.h>

#define N (10)

void quicksort(char a[], int low, int high);
int split(char a[], int low, int high);

int main(void)
{
char a[N];

printf("Enter letters to be sorted: ");

for (int i = 0; i < N; i++) {
scanf("%c", &a[i]);
}

quicksort(a, 0, N - 1);

printf("In sorted order: ");

for (int i = 0; i < N; i++) {
printf("%c ", a[i]);
}
printf("\n");

return 0;
}

void quicksort(char a[], int low, int high)
{
if (low < high) {
int middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
}

int split(char a[], int low, int high)
{
char part_element = a[low];

for (;;) {
while (low < high && part_element <= a[high]) {
high--;
}
if (low >= high) {
break;
}
a[low++] = a[high];

while (low < high && a[low] <= part_element) {
low++;
}
if (low >= high) {
break;
}
a[high--] = a[low];
}

a[high] = part_element;

return high;
}
``````

Does it not do everything it's supposed to?

EXAMPLE

``````> ./a.out
Enter letters to be sorted: aadircslne
In sorted order: a a c d e i l n r s
>
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download