简体   繁体   中英

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

我正在寻找一种简单易懂的算法来按字母顺序对C中的字符数组进行排序。

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;
}

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, ie

setlocale(LC_COLLATE, "");

只需尝试最简单的排序算法“ 冒泡排序”即可

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.

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);
    }

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM