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

一世执手 提交于 2020-02-25 22:31:07

问题


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


回答1:


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.




回答2:


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, "");




回答3:


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



回答4:


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.




回答5:


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




回答6:


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



回答7:


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;


来源:https://stackoverflow.com/questions/122649/what-would-be-the-simplest-way-to-alpha-sort-an-array-of-chars-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!