用C对数组排序?

编程入门 行业动态 更新时间:2024-10-23 18:33:11
本文介绍了用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 )

请参阅: www.cplusplus/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对数组排序?

本文发布于:2023-07-29 00:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!