-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial_sort.h
153 lines (117 loc) · 2.28 KB
/
serial_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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/* Serial Quick Sort and Quick Select implementation
* Tested here:
* sorting:
* https://leetcode.com/problems/sort-an-array/
*
* quick select:
* https://leetcode.com/problems/kth-largest-element-in-an-array
*
*/
#ifndef SERIAL_SORT_H
#define SERIAL_SORT_H
#include <stdio.h>
#include <stdlib.h>
/* TYPES */
typedef int elem;
/* GLOBALS */
void swap(elem* a, elem* b) {
elem swapvar = *a;
*a = *b;
*b = swapvar;
}
/* If a < b, return -1
* a > b, return 1
* a = b, return 0
*/
int cmp(elem* a, elem* b) {
if (*a < *b) {
return -1;
} else if (*a > *b) {
return 1;
} else {
return 0;
}
}
/*
* Partition a subarray about a pivot
*/
elem* partition(elem* l, elem* r, elem pivot) {
elem* c = l;
while(c <= r) {
if (cmp(l, &pivot) == -1) {
++l;
if (c < l) {
c = l;
}
continue;
}
if (cmp(r, &pivot) == 1) {
--r;
continue;
}
if (c < l) {
c = l;
continue;
}
if (cmp(c, &pivot) == -1) {
swap(c, l); ++l; continue;
}
if (cmp(c, &pivot) == 1) {
swap(c, r);
--r;
continue;
}
++c;
}
return r;
}
/**
* Perform bubble sort on a subarray
*/
void m_bubble_sort(elem* l, elem* r) {
if (l >= r) { return; }
for (elem* i = r; i >= l; --i) {
for (elem* j = l; j < i; ++j) {
if ((*j) >= (*(j + 1))) {
swap(j, j + 1);
} else {
break;
}
}
}
}
/**
* Perform quicksort on a subarray
*/
void m_qsort(elem* l, elem* r) {
if (l >= r) { return; }
elem* piv = rand() % (r - l) + l;
piv = partition(l, r, *piv);
m_qsort(l, piv - 1);
m_qsort(piv + 1, r);
}
/**
* Get Kth element of a subarray in sorted order
* in O(n) time, O(1) space.
*/
elem findKth(elem* l, elem* r, size_t k) {
if (k > (1 + (r - l))) {
fprintf(stderr, "ERROR: k(%ld) larger than total size(%ld) bytes(%ld)\n", k, (r - l), (r - l));
exit(EXIT_FAILURE);
}
elem* piv;
while(l < r) {
piv = rand() % (r - l) + l;
piv = partition(l, r, *piv);
if ((piv - l + 1) > k) {
r = piv - 1;
} else if ((piv - l + 1) < k) {
k -= (piv - l + 1);
l = piv + 1;
} else {
return *piv;
}
}
return *l;
}
#endif