Skip to content

Commit 4dbb91b

Browse files
Add 0912
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 2095ed9 commit 4dbb91b

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

0912_sort_an_array/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -o test sort.c

0912_sort_an_array/sort.c

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
5+
static void show(int *nums, int lo, int hi)
6+
{
7+
int i;
8+
for (i = lo; i <= hi; i++) {
9+
printf("%d ", nums[i]);
10+
}
11+
printf("\n");
12+
}
13+
14+
static inline void swap(int *a, int *b)
15+
{
16+
int t = *a;
17+
*a = *b;
18+
*b = t;
19+
}
20+
21+
static void quick_sort(int *nums, int lo, int hi)
22+
{
23+
int i, j, mid, pivot;
24+
25+
if (lo >= hi) {
26+
return;
27+
}
28+
29+
/* shuffle the pivot */
30+
mid = lo + (hi - lo) / 2;
31+
swap(&nums[mid], &nums[hi]);
32+
33+
i = lo - 1;
34+
j = hi;
35+
pivot = nums[hi];
36+
while (i < j) {
37+
/* For case of large amounts of consecutive duplicate elements, we
38+
* shall make the partition in the middle of the array as far as
39+
* possible. If the partition is located in the head or tail, the
40+
* performance might well be very bad for it.
41+
*/
42+
while (i < hi && nums[++i] < pivot) {}
43+
while (j > lo && nums[--j] > pivot) {}
44+
if (i < j) {
45+
swap(&nums[i], &nums[j]);
46+
}
47+
}
48+
49+
/* Loop invariant: i == j + 1 or i == j */
50+
swap(&nums[i], &nums[hi]);
51+
quick_sort(nums, lo, i - 1);
52+
quick_sort(nums, i + 1, hi);
53+
}
54+
55+
int main(int argc, char **argv)
56+
{
57+
int i, count = argc - 1;
58+
int *nums = malloc(count * sizeof(int));
59+
for (i = 0; i < count; i++) {
60+
nums[i] = atoi(argv[i + 1]);
61+
}
62+
63+
quick_sort(nums, 0, count - 1);
64+
show(nums, 0, count - 1);
65+
66+
return 0;
67+
}

0 commit comments

Comments
 (0)