forked from Privanom/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quicksort.c
74 lines (60 loc) · 1.15 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
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b);
int partition(int *a, int l, int h);
void quick_sort(int *a, int l, int h);
int main()
{
int size;
printf("Size: ");
scanf("%d", &size);
int *arr = malloc(size * sizeof(int));
printf("Array elements: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
quick_sort(arr, 0, size - 1);
printf("Sorted array:");
for (int i = 0; i < size; i++)
{
printf(" %d", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
return;
}
int partition(int a[], int l, int h)
{
int i = l, j = l, p = h;
while (i < h)
{
if (a[i] < a[p])
{
swap(&a[i], &a[j]);
j++;
}
i++;
}
swap(&a[p], &a[j]);
return j;
}
void quick_sort(int a[], int l, int h)
{
int p;
if (l < h)
{
p = partition(a, l, h);
quick_sort(a, l, p - 1);
quick_sort(a, p + 1, h);
}
return;
}