Skip to content

Commit c0e9726

Browse files
quick sort (#90)
1 parent 4af5047 commit c0e9726

File tree

2 files changed

+67
-2
lines changed

2 files changed

+67
-2
lines changed

sorts/quick_sort.c

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,26 @@
22
#include <stdlib.h>
33
#include <time.h>
44

5+
void swap(int *arr, int i, int j) {
6+
int temp = arr[i];
7+
arr[i] = arr[j];
8+
arr[j] = temp;
9+
}
10+
511
int partition(int *arr, int low, int high) {
612
int pivot = arr[low];
713
while (low < high) {
814
while (low < high && arr[high] >= pivot) {
915
high--;
1016
}
11-
arr[low] = arr[high];
1217
while (low < high && arr[low] <= pivot) {
1318
low++;
1419
}
15-
arr[high] = arr[low];
20+
if (low < high) {
21+
swap(arr, low, high);
22+
low++;
23+
high--;
24+
}
1625
}
1726
arr[low] = pivot;
1827
return low;

sorts/quick_sort_easy_partition.c

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <assert.h>
2+
#include <stdlib.h>
3+
#include <time.h>
4+
5+
int partition(int *arr, int low, int high) {
6+
int len = high - low + 1;
7+
int temp[len];
8+
int j = 0;
9+
int k = len - 1;
10+
int pivot = arr[low];
11+
for (int i = low + 1; i <= high; ++i) {
12+
if (arr[i] <= pivot) {
13+
temp[j] = arr[i];
14+
j++;
15+
} else {
16+
temp[k] = arr[i];
17+
k--;
18+
}
19+
}
20+
assert(j == k);
21+
temp[j] = pivot;
22+
for (int i = 0; i < len; ++i) {
23+
arr[low + i] = temp[i];
24+
}
25+
return low + j; /* return low + k */
26+
}
27+
28+
void quickSort(int *arr, int low, int high) {
29+
if (low < high) {
30+
int pivotIndex = partition(arr, low, high);
31+
quickSort(arr, low, pivotIndex - 1);
32+
quickSort(arr, pivotIndex + 1, high);
33+
}
34+
}
35+
36+
void test() {
37+
const int size = 10;
38+
int *arr = (int *) calloc(size, sizeof(int));
39+
40+
/* generate size random numbers from 0 to 100 */
41+
for (int i = 0; i < size; i++) {
42+
arr[i] = rand() % 100;
43+
}
44+
quickSort(arr, 0, size - 1);
45+
for (int i = 0; i < size - 1; ++i) {
46+
assert(arr[i] <= arr[i + 1]);
47+
}
48+
free(arr);
49+
}
50+
51+
int main() {
52+
/* initial random number generator */
53+
srand(time(NULL));
54+
test();
55+
return 0;
56+
}

0 commit comments

Comments
 (0)