1
using
System;
2
using
System.Collections.Generic;
3
using
System.Text;
4
5
namespace
QuickSort
6
{
7
class Program
8
{
9
static void Main(string[] args)
10
{
11
int[] a = new int[] { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
12
13
QuickSort q = new QuickSort();
14
q.Init(a);
15
q.Sort(0, a.Length - 1);
16
17
int[] r = q.GetResult();
18
19
if (r != null)
20
{
21
for (int i = 0; i < r.Length; i++)
22
{
23
System.Console.WriteLine(r[i]);
24
}
25
}
26
}
27
}
28
29
class QuickSort
30
{
31
private int[] _toBeSort;
32
33
private bool _isSort;
34
35
public void Init(int[] toBeSort)
36
{
37
_isSort = false;
38
_toBeSort = toBeSort;
39
}
40
41
public int[] GetResult()
42
{
43
if (_isSort)
44
{
45
return _toBeSort;
46
}
47
else
48
{
49
return null;
50
}
51
}
52
53
public void Sort(int startIndex, int endIndex)
54
{
55
if (_toBeSort == null)
56
{
57
throw new Exception();
58
}
59
60
if (endIndex > 1 + startIndex)
61
{
62
int part = partition(startIndex, endIndex);
63
64
//_toBeSort[part]已经在合适的位置上了,无需再次考虑。
65
Sort(startIndex, part - 1);
66
Sort(part + 1, endIndex);
67
}
68
69
_isSort = true;
70
}
71
72
private int partition(int startIndex, int endIndex)
73
{
74
int part = startIndex;
75
76
int mid = _toBeSort[startIndex];
77
78
int si = startIndex + 1;
79
int bi = endIndex;
80
int temp = 0;
81
82
while (si < bi)
83
{
84
while (_toBeSort[si] < mid)
85
{
86
si++;
87
if (si == endIndex)
88
{
89
break;
90
}
91
}
92
93
while (_toBeSort[bi] > mid)
94
{
95
bi--;
96
}
97
98
if (si < bi)
99
{
100
temp = _toBeSort[bi];
101
_toBeSort[bi] = _toBeSort[si];
102
_toBeSort[si] = temp;
103
si++;
104
bi--;
105
}
106
}
107
108
temp = _toBeSort[bi];
109
_toBeSort[bi] = _toBeSort[startIndex];
110
_toBeSort[startIndex] = temp;
111
112
part = bi;
113
114
return part;
115
}
116
}
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
