-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquickSort.c
85 lines (80 loc) · 1.45 KB
/
quickSort.c
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
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
if (a == b)
{
return;
}
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int *get_median(int *arr, int len)
{
int first = arr[0];
int last = arr[len - 1];
int mid = arr[len / 2];
if ((first > mid) ^ (first > last))
{
return arr;
}
else if ((last > mid) ^ (last > first))
{
return arr + len - 1;
}
else
{
return arr + len / 2;
}
}
void quick_sort(int *arr, int len)
{
if (len <= 1)
{
return;
}
swap(arr, get_median(arr, len));
int pivot = *arr;
int *low = arr, *high = arr + len - 1;
while (low < high)
{
while (*high <= pivot && high > low)
{
high--;
}
while (*low >= pivot && low < high)
{
low++;
}
swap(low, high);
}
swap(arr, high);
int *right = high + 1;
int *left = arr;
int left_len = high - arr;
int right_len = len - left_len - 1;
quick_sort(left, left_len);
quick_sort(right, right_len);
}
int main(void)
{
int n;
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
quick_sort(arr, n);
for (int i = 0; i < n; i++)
{
printf("%d", arr[i]);
if (i != n - 1)
{
printf(" ");
}
}
free(arr);
return 0;
}