简体   繁体   English

在C语言中对字符数组进行alpha排序的最简单方法是什么?

[英]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. C中的字符具有恰好是按顺序的数字值,因此您只需将字符视为整数即可。 the C standard library includes a 'qsort' function. C标准库包含一个“ qsort”功能。 Use that ( man qsort on a linux-like system). 使用它(在类似linux的系统上使用man qsort )。 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 . 如果您想了解quicksort算法(那是您应该学习的算法,因为您将实际使用它),请参阅Wikipedia

Use the qsort method: 使用qsort方法:

#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. 如果结果适用于人类,则最好使用strcoll。 It is slower then strcmp or strcasecmp but it accounts for non-english characters. 它比strcmp或strcasecmp慢,但它说明了非英语字符。 If you are going to use it don't forget to set your locale for LC_COLLATE, ie 如果要使用它,请不要忘记为LC_COLLATE设置语言环境,即

setlocale(LC_COLLATE, ""); 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 . 如果是后者,则使用C的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... 这是java和int而不是char,但是您可以轻松地对其进行适应...

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): 这是非常简单且渐近最快的(N是数组的大小):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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