I'm looking for a simple, easy to understand algorithm to alphabetically sort an array of characters in C.
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);
}
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.
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;
}
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.
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, "");
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;