forked from mit-pdos/xv6-public
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.c
74 lines (60 loc) · 1.31 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
#include "types.h"
#include "stat.h"
#include "user.h"
int partition(int* array, int low, int high);
void quicksort(int* array, int low, int high);
int main(int argc, char* args[])
{
if(argc <= 1)
{
printf(1, "Error: Quicksort needs more than 1 argument\n");
exit();
}
int* numbers = malloc(sizeof(int) * (argc - 1));
for(int i = 1; i < argc; i++)
{
numbers[i - 1] = atoi(args[i]);
}
quicksort(numbers, 0, (argc - 2));
for(int i = 0; i < (argc - 1); i++)
{
if(i == (argc - 2))
{
printf(2, "%d\n", numbers[i]);
}
else
{
printf(2, "%d, ", numbers[i]);
}
}
free(numbers);
exit();
}
void quicksort(int* array, int low, int high)
{
if(low < high)
{
int p = partition(array, low, high);
quicksort(array, low, p - 1);
quicksort(array, p + 1, high);
}
}
int partition(int* array, int low, int high)
{
int pivot = array[high];
int i = low;
for(int j = low; j < high; j++)
{
if(array[j] < pivot)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
}
}
int temp = array[i];
array[i] = array[high];
array[high] = temp;
return i;
}