Bucket sort the problem - non-contrast sort

Subject description:  

  Comparative not sort, sort of an array to achieve
  time complexity of O (N), the additional space complexity O (N)

Problem-solving ideas:
  the use of bucket sort of thinking, apply an additional array, called barrel, to record the number of times the number that appears, then the output can, but the bucket sort is generally applicable to digital ordering elements 0-9, just because the barrel 0-9 application space, if the array element 999, the space barrels apply for 0-999 at least, that does not apply.


  Extended: Use the map to achieve a barrel, then you can achieve any array sorting bucket

 

Code:

  

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <map>
 5 
 6 using namespace std;
 7 
 8 //使用桶数组
 9 void Test01(const int array[], int N)
10 {
11     int TT[10] = { 0 };
12     for (int i = 0; i < N; ++i)
13         TT[array[i]]++;
14     for (int i = 0; i < 10; ++i)
15         for (int j = 0; j < TT[i]; ++j)
16             cout << i << "  ";
17 
18     cout << endl << "*******************" << endl;
19 }
20 
21 
22 //使用map
23 void Test02(const int array[], int N)
24 {
25     map<int, int>M;
26     for (int i = 0; i < N; ++i)
27         M[array[i]]++;
28 
29     for (auto ptr = M.cbegin(); ptr != M.cend(); ++ptr)
30         for (int j = 0; j < ptr->second; ++j)
31             cout << ptr->first << "  ";
32     cout << endl << "*******************" << endl;
33 
34 
35 
36 }
37 
38 void NoSort()
39 {
40     int arr[] = { 9,1,4,8,5,6,7,1,2,5,4,9,0,6 };
41     Test01(arr, sizeof(arr) / sizeof(arr[0]));
42     Test02(arr, sizeof(arr) / sizeof(arr[0]));
43 
44 }

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/10987856.html