Repository navigation
Expand file tree
/
Copy pathquick_sort.h
More file actions
83 lines (72 loc) · 1.93 KB
/
Copy pathquick_sort.h
File metadata and controls
83 lines (72 loc) · 1.93 KB
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
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
/*******************************************************************************
* DANIEL'S ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
*
* QUICKSORT
*
* Features:
* 1. sort array in O(nlogn) time.
* 2. most generic fast sorting algorithm
*
* http://en.wikipedia.org/wiki/Quick_sort
*
******************************************************************************/
#ifndef __QUICKSORT_H__
#define __QUICKSORT_H__
#include <generic.h>
#include <cassert>
namespace alg {
/**
* Return median of begin, middle, and end.
* Order these and hide the pivot.
*/
template<typename T>
static const T & __median3(T list[], int begin, int end) {
assert(begin + 2 <= end);
int middle = end - (end - begin) / 2;
if (list[middle] < list[begin])
swap(list[middle], list[begin]);
if (list[end] < list[begin])
swap(list[end], list[begin]);
if (list[end] < list[middle])
swap(list[end], list[middle]);
//Place pivot at position [end - 1]
swap(list[middle], list[end - 1]);
return list[end - 1];
}
/**
* the quick-sort partition routine
*/
template<typename T>
static int __partition(T list[],int begin, int end) {
T pivot = __median3<T>(list, begin, end);
int i = begin;
int j = end - 1;
while(i < j) {
while(list[++i] < pivot) {}
while(pivot < list[--j]) {}
if(i < j)
swap(list[i],list[j]);
}
swap(list[i],list[end - 1]);
return i; // final pivot position
}
/**
* quick sort an array of range [begin, end]
*/
template<typename T>
static void quicksort(T list[],int begin,int end) {
if( begin + 1 < end) {
int pivot_idx = __partition<T>(list, begin, end);
quicksort(list, begin, pivot_idx-1);
quicksort(list, pivot_idx+1, end);
} else if ( begin + 1 == end) {
if (list[begin + 1] > list[end])
swap(list[begin + 1], list[end]);
}
}
}
#endif //