哪种是对以下数组进行排序的最佳排序技术,如果有重复项,如何处理它们:
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对数组排序?
发布评论