Sort Algorithms

Outline

  • Elementary Sort
  • MergeSort
  • QuickSort
  • Priority Queues

快速排序

1
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

template<typename T, int N>
int partition(T(&a)[N], int lo, int hi)
{
int i = lo, j = hi + 1;
T v = a[lo];
while (true)
{
while (a[++i] < v) if (i == hi) break;
while (a[--j] > v) if (j == lo) break;
if (i >= j) break;
exch(a, i, j);
}
exch(a, lo, j);
return j;




}


template<typename T,int N>
void exch(T (&a)[N], int i , int j)
{
T tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}

template<typename T, int N>
void sort(T(&a)[N])
{
sort(a, 0, N - 1);
}

template<typename T, int N>
void sort(T ( &a )[N], int lo, int hi)
{
if (hi <= lo) return;
int j = partition(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}