-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort.h
81 lines (73 loc) · 1.69 KB
/
quicksort.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// Created by odin on 3/1/17.
//
#ifndef QUICKSORT_QUICKSORT_H
#define QUICKSORT_QUICKSORT_H
template <typename T>
class quicksort {
private:
static const int THRESHOLD = 2; //TODO: change to eks 12 when insertion sort is done
static void swap(T *a, T *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
static void insertionSort(T *arr, int size)
{
//TODO: make this word :P
T *arrend = arr+size-1;
T *current;
bool run = true;
while(run)
{
current = arr;
run = false;
while(current != arrend)
{
if(*current > *(current+1)) {
swap(current, current + 1);
run = true;
}
current++;
}
}
}
public:
static void sort(T *arr, int size)
{
T *i = arr;
T *j = arr+size-1;
T pivot = *(arr+size/2);
while(i < j)
{
while(*i < pivot && i < j)
++i;
while(*j > pivot && i < j)
--j;
if(*i == *j && i != j) {
++i;
}
else if(i < j) {
swap(i, j);
}
}
int size_left = i-arr;
int size_right = arr+size-i;
if(size_left > THRESHOLD)
{
sort(arr,size_left);
} else if(size_left > 2)
{
insertionSort(arr,size_left);
}
if(size_right > THRESHOLD)
{
sort(i,size_right);
} else if(size_right > 2)
{
insertionSort(arr,size_left);
}
}
};
#endif //QUICKSORT_QUICKSORT_H