int a[] = {12,13,12,13,19,18,15,12,15,16,17},要求对数组a进行排序,要求时间复杂度为O(N)
我们所知道的常规排序中,最优的解法也就是O(N*log2^N),那如何做到时间复杂度为O(N)呢?
运用哈希算法的思想就可以优化算法为O(N)
void Sort(int* a, int n) { assert(a); const int N = 20; int b[N] = { 0 }; for (int i = 0; i < n; i++) { int key = a[i]; ++b[key]; } int index = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < b[i]; j++) { a[index] = i; ++index; } } } int main() { int arr[] = { 12, 13, 12, 13, 19, 18, 15, 12, 15, 16, 17 }; int sz = sizeof(arr) / sizeof(arr[0]); Sort(arr, sz); for (int i = 0; i < sz; i++) { cout << arr[i] << " "; } cout << endl; cin.get(); return 0; }