-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathquick_sort.h
62 lines (54 loc) · 1.37 KB
/
quick_sort.h
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
/*******************************************************************************
* 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 ALGO_QUICKSORT_H__
#define ALGO_QUICKSORT_H__
#include <generic.h>
namespace alg {
/**
* the quick-sort partition routine
*/
template<typename T>
static int partition_(T list[],int begin, int end) {
int pivot_idx = RANDOM(begin,end);
T pivot = list[pivot_idx];
swap(list[begin], list[pivot_idx]);
int i = begin + 1;
int j = end;
while(i <= j) {
while((i <= end) && (list[i] <= pivot))
i++;
while((j >= begin) && (list[j] > pivot))
j--;
if(i < j)
swap(list[i],list[j]);
}
swap(list[begin],list[j]);
return j; // 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 < end) {
int pivot_idx = partition_<T>(list, begin, end);
quicksort(list, begin, pivot_idx-1);
quicksort(list, pivot_idx+1, end);
}
}
}
#endif //