c - 在 C 中对数组进行排序?

标签 c algorithm sorting

对以下数组进行排序的最佳排序技术是什么,如果有重复项如何处理:

int a= {1,3,6,7,1,2};

还有哪一种是最好的排序技术?

void BubbleSort(int a[], int array_size)
{
    int i, j, temp;
    for (i = 0; i < (array_size - 1); ++i)
    {
        for (j = 0; j < array_size - 1 - i; ++j )
        {
            if (a[j] > a[j+1])
            {
                temp = a[j+1];
                a[j+1] = a[j];
                a[j] = temp;
            }
        }
    }
}

最佳答案

在 C 中,您可以使用内置的 qsort 命令:

int compare( const void* a, const void* b)
{
     int int_a = * ( (int*) a );
     int int_b = * ( (int*) b );

     if ( int_a == int_b ) return 0;
     else if ( int_a < int_b ) return -1;
     else return 1;
}

qsort( a, 6, sizeof(int), compare )

参见:http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


回答问题的第二部分:最佳(基于比较的)排序算法是运行 O(n log(n)) 比较的算法。有几种具有此属性(包括快速排序、合并排序、堆排序等),但使用哪一种取决于您的用例。

作为旁注,如果您对自己的数据有所了解,有时您可以比 O(n log(n)) 做得更好 - 请参阅关于 Radix Sort 的维基百科文章

关于c - 在 C 中对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3893937/

相关文章:

java - Collections.sort 是否保持相等元素的顺序?

sorting - PS对象排序

python - 带有列表的字典 : Fastest way to get the key corresponding to the minimum value of the fourth list item?

c++ - 当.so是纯c的时候,用c++/shell脚本写核心主程序是不是一个好的设计?

c++ - 随机排列非重复序列

algorithm - 方形拼图解

algorithm - 大于或等于目标的数的倍数之和,优化

c - 在 shell 原型(prototype)中实现 globbing

c - 如何在 C 中获取 Ruby 对象的类?

C数组初始化