C中的数组排序提示 [英] C Array sorting tips

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

问题描述

  A = [1,3,6,7,1,2]
 

这是最好的排序方法进行排序如下数组,如果有重复如何处理它们。 同时这也是所有的最好的分拣技术......

 无效冒泡(INT A [],INT ARRAY_SIZE)
 {
 INT I,J,温度;
 对于(I = 0; I&≤(ARRAY_SIZE  -  1); ++ⅰ)
 {
      为(J = 0; J< ARRAY_SIZE  -  1  - 我; ++ j)条
      {
           如果(一个[j]的>一种[J + 1])
           {
                TEMP =一[J + 1];
                一[J + 1] = A [J]。
                一个[J] =气温;
           }
      }
 }
 }
 

解决方案

在C语言中,你可以使用内置的的qsort 命令:

  INT比较(常量无效*一,常量无效* B)
{
     INT int_a = *((INT *)一);
     INT int_b = *((INT *)B);

     如果(int_a == int_b)返回0;
     否则,如果(int_a< int_b)返回-1;
     否则返回1;
}

的qsort(一个,6,的sizeof(int)的,比较)
 

请参阅: http://www.cplusplus.com/reference/clibrary/cstdlib /的qsort /


要回答你问题的第二部分:最优(基于比较)排序算法是一个具有为O(N日志(n))的比较。有几个具有这种性质(包括快速排序,归并排序,堆排序等),但使用哪一个取决于你的使用情况。

作为一个方面说明,您可以有时为O做的更好(N日​​志(n))的,如果你知道一些关于你的数据 - 看到的基数排序

       a=[1,3,6,7,1,2]

Which is the best sorting technique to sort the following array and if there are duplicates how to handle them. 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;
           }
      }
 }
 }   

解决方案

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 )

see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


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.

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天全站免登陆