基本排序方法及分析(八):CoungtingSort 計數(shù)排序
計數(shù)排序?qū)[0],...,a[n-1]進(jìn)行排序,其中1 <= a[i] <= m計數(shù)排序不是基于比較的排序方法,從而最壞情形下的運(yùn)行時間也不受比較的排序方法最快O(nlgn)的限制。
計數(shù)排序的運(yùn)行時間是O(n+m)
1
/**//**
2
* Countying sort計數(shù)排序
3
* 對a[0],
,a[n-1]進(jìn)行排序,其中1 <= a[i] <= m
4
*/
5
6
#include <iostream>
7
#include <cstdlib>
8
9
using namespace std;
10
11
void print(int* a , int n)
12

{
13
for(int i = 0; i < n ; i++)
14
cout << a[i];
15
cout << endl;
16
}
17
18
//對a[0],
,a[n-1]進(jìn)行排序,其中1 <= a[i] <= m
19
void Counting_Sort(int *a, int n , int m)
20

{
21
int *c = new int[m];
22
int *temp = new int[n];
23
24
//初始設(shè)為0
25
for(int i = 0; i < m ; i++)
26
{
27
c[i] = 0;
28
}
29
30
//c[i-1]中存儲值為i的個數(shù)
31
for(int i = 0; i < n; i++)
32
{
33
c[a[i]-1] += 1;
34
}
35
36
//c[i-1]中存儲值小于等于i的個數(shù)
37
for(int i = 1; i < m; i++)
38
{
39
c[i] = c[i] + c[i-1];
40
}
41
42
//排序
43
for(int i = n-1; i >= 0; i--)
44
{
45
temp[c[a[i]-1]-1] = a[i];
46
c[a[i]-1]--;
47
}
48
49
//從臨時數(shù)組轉(zhuǎn)到a
50
for(int i = 0; i < n; i++)
51
{
52
a[i] = temp[i];
53
}
54
}
55
56
int main()
57

{
58
int a[5] =
{4,1,3,4,3};
59
60
print(a,5);
61
62
Counting_Sort(a,5,4);
63
64
print(a,5);
65
66
system("pause");
67
return 0;
68
}
69
70


2

3


4

5

6

7

8

9

10

11

12



13

14

15

16

17

18


19

20



21

22

23

24

25

26



27

28

29

30

31

32



33

34

35

36

37

38



39

40

41

42

43

44



45

46

47

48

49

50

51



52

53

54

55

56

57



58



59

60

61

62

63

64

65

66

67

68

69

70

posted on 2010-01-18 15:50 幸運(yùn)草 閱讀(458) 評論(0) 編輯 收藏 引用 所屬分類: Algorithms