-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqsort.c
60 lines (50 loc) · 1009 Bytes
/
qsort.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
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int* a, int low, int high)
{
int pivotloc = low;
int pivot = a[low];
int i;
for (i = low +1; i <= high; i++) {
if (a[i] < pivot) {
swap(&a[++pivotloc], &a[i]);
}
}
swap(&a[pivotloc], &a[low]);
return pivotloc;
}
void quicksort(int* arr, int low, int high)
{
int pivot;
if (low < high) {
pivot = partition(arr, low, high);
quicksort(arr, low, pivot-1);
quicksort(arr, pivot+1, high);
}
}
int main(int argc, char** argv) {
int i, sz;
if (argc == 2) {
sz = atoi(argv[1]);
} else
sz = 20;
int *arr = malloc (20* sizeof(int));
for (i=0;i<sz; i++) {
arr[i] = (rand() + 50) % (500 +1);
}
printf("unsorted array is: \n");
for (i=0; i<sz; i++)
printf("%d ", arr[i]);
printf("\n");
quicksort(arr, 0, sz-1);
printf("Sorted array is: \n");
for (i=0; i<sz; i++)
printf("%d ", arr[i]);
printf("\n");
}