交换排序是一类借助于交换元素的值来进行排序的方法,最简单的交换排序是人们熟知的"冒泡排序",另一种是"快速排序",快速排序是对冒泡排序的改进.今天用C#写了两个算法的实现,用的是对于数组的扩展方法.代码贴在下面,方便以后查看.

Code
1
using System;
2
3
namespace Whut.sorting
4

{
5
class SortClass
6
{
7
static void Main(string[] args)
8
{
9
int[] x =
{2,6,52,41,48,57,625 ,321,315,654,564,56465,4564894,13432,13,12,1,5,464,
10
3,13,15,4,1321,4,31,315,64,13,1654,31,21,54,1,321,654,1,165,41,3165,4,
11
26,59,798,1,4,7132123,16,46,321};
12
x.bubbleSort();
13
//x.quickSort();
14
foreach (var item in x)
15
{
16
Console.Write(item+" ");
17
}
18
Console.Read();
19
}
20
21
}
22
23
24
public static class Sorting
25
{
26
公有方法#region 公有方法
27
28
public static void bubbleSort(this int[] x, int low, int high)
29
{
30
bool change;
31
int lastchange;
32
33
for (int i = high; i > low; i=lastchange)
34
{
35
change = false;
36
lastchange = low;
37
38
for (int j = low; j < i; j++)
39
{
40
if (x[j] > x[j + 1])
41
{
42
int temp = x[j];
43
x[j] = x[j + 1];
44
x[j + 1] = temp;
45
46
change = true;
47
lastchange = j;
48
}
49
}
50
51
if (!change)
52
{
53
break;
54
}
55
}
56
}
57
58
public static void bubbleSort(this int[] x)
59
{
60
bubbleSort(x, 0, x.Length - 1);
61
}
62
63
public static void quickSort(this int[] x, int low, int high)
64
{
65
if (low > high)
66
{
67
return;
68
}
69
int k = partition(x, low, high);
70
quickSort(x, low, k - 1);
71
quickSort(x, k + 1, high);
72
73
}
74
75
public static void quickSort(this int[] x)
76
{
77
quickSort(x, 0, x.GetUpperBound(0));
78
}
79
80
#endregion
81
82
83
私有函数#region 私有函数
84
85
private static int partition(int[] x, int low, int high)
86
{
87
Random ran = new Random();
88
swap(x[low], x[ran.Next(low, high)]);
89
int pivotkey = x[low];
90
while (low < high)
91
{
92
while (low < high && x[high] >= pivotkey)
93
{
94
high--;
95
}
96
x[low++] = x[high];
97
98
while (low < high && x[low] <= pivotkey)
99
{
100
low++;
101
}
102
x[high--] = x[low];
103
}
104
x[low] = pivotkey;
105
return low;
106
}
107
108
private static void swap(int a, int b)
109
{
110
int temp = a;
111
a = b;
112
b = temp;
113
}
114
115
#endregion
116
117
118
}
119
}
120
不知道有有没有错误或者值得改进的地方,欢迎大家给意义和建议.