用C对数组排序? [英] Sorting an array in C?

查看:88
本文介绍了用C对数组排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Which is the best sorting technique to sort the following array and if there are duplicates how to handle them:

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

还有,这是最好的排序技术吗?

Also which is the best sorting technique of all?

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 命令:

In C, you can use the built in qsort command:

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))比较一起运行的算法。有几个具有此属性的属性(包括快速排序,合并排序,堆排序等),但是要使用哪个取决于您的用例。

To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.

旁注,如果您对数据有所了解,有时可以比O(n log(n))做得更好-请参阅基数排序

As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort

这篇关于用C对数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆