-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.h
97 lines (79 loc) · 2.08 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#pragma once
#ifndef _QUICKSORT_H
#define _QUICKSORT_H
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename Comparable>
void insertionSort(vector<Comparable>& a, int left, int right)
{
for (int p = left + 1; p <= right; p++)
{
Comparable tmp = a[p];
int j;
for (j = p; j > left && tmp < a[j - 1]; j--)
a[j] = a[j - 1];
a[j] = tmp;
}
}
/**
* Standard swap
*/
template <typename Comparable>
inline void swap(Comparable& obj1,
Comparable& obj2)
{
Comparable tmp = obj1;
obj1 = obj2;
obj2 = tmp;
}
/** Return median of left, center, and right.
* Order these and hide the pivot.
*/
template <typename Comparable>
const Comparable& median3(vector<Comparable>& a,
int left, int right)
{
int center = (left + right) / 2;
if (a[center] < a[left])
swap(a[left], a[center]);
if (a[right] < a[left])
swap(a[left], a[right]);
if (a[right] < a[center])
swap(a[center], a[right]);
// Place pivot at position right - 1
swap(a[center], a[right - 1]);
return a[right - 1];
}
template <typename Comparable>
void quicksort(vector<Comparable>& a,
int left, int right)
{
if (left + 10 <= right)
{
Comparable pivot = median3(a, left, right);
// Begin partitioning
int i = left, j = right - 1;
for (; ; )
{
while (a[++i] < pivot) {}
while (pivot < a[--j]) {}
if (i < j)
swap(a[i], a[j]);
else
break;
}
swap(a[i], a[right - 1]); // Restore pivot
quicksort(a, left, i - 1); // Sort small elements
quicksort(a, i + 1, right); // Sort large elements
}
else // Do an insertion sort on the subarray
insertionSort(a, left, right);
}
template <typename Comparable>
void quickSort(vector<Comparable>& a)
{
quicksort(a, 0, a.size() - 1);
}
#endif