-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathquick_sort.c
45 lines (37 loc) · 803 Bytes
/
quick_sort.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
#include <stdio.h>
#include <stdlib.h>
#include "values.c"
void quicksort(int v[], int n);
void swap(int v[], int i, int j);
int main()
{
quicksort(numbers, NELEMS(numbers));
printf("sorted numbers:\n");
for (int i = 0; i < NELEMS(numbers); i++)
{
printf("%d, ", numbers[i]);
}
printf("\n");
return 0;
}
void quicksort(int v[], int n)
{
int last = 0;
if (n <= 1)
return;
swap(v, 0, rand() % n); /* move pivot to v[0] */
for (int i = 0; i < n; i++)
if (v[i] < v[0])
swap(v, ++last, i);
swap(v, 0, last);
quicksort(v, last);
quicksort(v + last + 1, n - last - 1);
}
/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}