根据《算法设计与分析基础》中对归并排序的描述,写了一分C#代码实现。
具体的实现代码如下:
1
using
System;
2
using
System.Collections.Generic;
3
using
System.Text;
4
5
namespace
MergeSort
6
{
7
class Program
8
{
9
static void Main(string[] args)
10
{
11
Program p = new Program();
12
13
int[] a = new int[] { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
14
15
p.Sort(a);
16
17
for (int i = 0; i < a.Length; i++)
18
{
19
System.Console.WriteLine(a[i]);
20
}
21
}
22
23
/// <summary>
24
/// 利用归并排序按由下到大的顺序排序
25
/// </summary>
26
/// <param name="toBeSort"></param>
27
/// <returns></returns>
28
public int[] Sort(int[] toBeSort)
29
{
30
if (toBeSort.Length == 0)
31
{
32
throw new Exception("Sort array Error!");
33
}
34
35
if (toBeSort.Length > 1)
36
{
37
int[] part1 = Sort(get1Part(toBeSort));
38
int[] part2 = Sort(get2Part(toBeSort));
39
40
merger(part1, part2, toBeSort);
41
}
42
43
return toBeSort;
44
}
45
46
/// <summary>
47
/// 将part1和part2按照由小到大的顺序归并到数组toBeSort中
48
/// </summary>
49
/// <param name="part1"></param>
50
/// <param name="part2"></param>
51
/// <param name="toBeSort"></param>
52
private void merger(int[] part1, int[] part2, int[] toBeSort)
53
{
54
int index = 0;
55
int i1 = 0;
56
int i2 = 0;
57
58
while (i1 < part1.Length && i2 < part2.Length)
59
{
60
if (part1[i1] < part2[i2])
61
{
62
toBeSort[index] = part1[i1];
63
i1++;
64
}
65
else
66
{
67
toBeSort[index] = part2[i2];
68
i2++;
69
}
70
71
index++;
72
}
73
74
while (i1 < part1.Length)
75
{
76
toBeSort[index] = part1[i1];
77
index++;
78
i1++;
79
}
80
81
while (i2 < part2.Length)
82
{
83
toBeSort[index] = part2[i2];
84
index++;
85
i2++;
86
}
87
}
88
89
/// <summary>
90
/// Get the second part of the array.
91
/// </summary>
92
/// <param name="toBeSort">The array to be sort.</param>
93
/// <returns>The second part of the array.</returns>
94
private int[] get2Part(int[] toBeSort)
95
{
96
int len = toBeSort.Length - toBeSort.Length / 2;
97
int[] part2 = new int[len];
98
99
Array.Copy(toBeSort, toBeSort.Length / 2, part2, 0, len);
100
101
return part2;
102
}
103
104
/// <summary>
105
/// Get the first part of the array.
106
/// </summary>
107
/// <param name="toBeSort">The array to be sort.</param>
108
/// <returns>The first part of the array.</returns>
109
private int[] get1Part(int[] toBeSort)
110
{
111
int len = toBeSort.Length / 2;
112
int[] part1 = new int[len];
113
114
Array.Copy(toBeSort, part1, len);
115
116
return part1;
117
}
118
}
119
}
120

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

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

对于分治法的效率分析,有一个通用的公示可以使用:通用分治递推公式。