479

9
+1  Q:

## What would be the simplest way to alpha sort an array of chars in C?

I'm looking for a simple, easy to understand algorithm to alphabetically sort an array of characters in C.

+1  A:
Buddy I already know how to use the Google, but I definitely preffer to rely on the expertise and reliability of the stackoverflow community.
A:

Easy? Do a bubble sort.

This is java and int rather than char, but you can easily adapt it...

``````int[] bubble(int a[])
{
for (int i = a.length; --i>=0; )
{
for (int j = 0; j<i; j++)
{
if (a[j] > a[j+1])
{
int T = a[j];
a[j] = a[j+1];
a[j+1] = T;
}
}
}
return(a);
}
``````
surely if you want simple you might as well go for insertion sort or selection sort, rather than bubble sort?
Thanks but I can't use Java, I should implement the solution in plain C.
+5  A:

characters in C have numeric values that happen to be in order, so you just treat your characters like integers. the C standard library includes a 'qsort' function. Use that (`man qsort` on a linux-like system). You might have to convert upper-case letters to lowercase to simplify things, but that's trivial. If you want to understand the quicksort algorithm (that's the one you should learn, because you'll actually use it), see Wikipedia.

+1  A:

Just try Bubble Sort that's the easiest sorting algorithm.

Not as slow as [Bogosort](http://en.wikipedia.org/wiki/Bogosort)
Never claim an algorithm is the "slowest" for a particular task. One can always write a slower one. :)
Heh indeed, I'll remove the 'slowest'. ;)
IMHO, insertion sort is easier then bubble sort.
A:

Sounds like a homework assignment to me. Try reading wikipedia ...

Sounds like offensive to me. Try being more educated.
+2  A:

Use the qsort method:

``````#include <stdlib.h>

int char_compare (const void * a, const void * b)
{
return *(const char *)a - *(const char *)b;
}

int main(){
const char char_array[] = { 'c', 'a', 'b' };

qsort (char_array, 3, sizeof(char), char_compare);

return 0;
}
``````
That sorts an array of strings, he asked to sort an array of characters.
oops yes. thanks for noticing that.
+1  A:

I wonder if you are really looking for an algorithm or just a way to solve the problem? If the latter, then use C's qsort.

If you want an algorith, go for Insertion sort or Selection sort, as they're very simple to understand.

+2  A:

If the result is intended for humans, it is better to use strcoll. It is slower then strcmp or strcasecmp but it accounts for non-english characters. If you are going to use it don't forget to set your locale for LC_COLLATE, i.e.

setlocale(LC_COLLATE, "");

A:

This is pretty simple and asymptotically fastest (N is size of array):

``````const unsigned char in[N];
unsigned char out[N], *p=out;
size_t cnt[N]={0}, i, j;
for (i=0; i<COUNT; i++) cnt[in[i]]++;
for (i=0; i<256; i++) for (j=cnt[i]; j; j--) *p++=i;
``````