-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqsort.c
More file actions
73 lines (65 loc) · 1.13 KB
/
qsort.c
File metadata and controls
73 lines (65 loc) · 1.13 KB
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 <stdio.h>
void quickSort(int A[], int p, int r);
int partition(int A[], int p, int r);
void printA(int A[],int,int);
void swap(int *y, int *x);
#define MAX 10
#define K 1
int main(int argc, char *argv[])
{
int A[] = {5, 2, 6, 9, 7, 4, 8, 4, 3, 10};
printA(A, 0, MAX);
quickSort(A, 0, MAX-1);
printA(A, 0, MAX);
return 0;
}
void quickSort(int A[], int p, int r)
{
if (K+p < r)//use the K only for question 5
{
int q = partition(A, p, r);
quickSort(A, p, q);
quickSort(A, q+1, r);
}
}
int partition(int A[], int p, int r)
{
int x = A[p];
int i = p - 1;
int j = r + 1;
while (TRUE)
{
do
{
j--;
}
while (A[j] > x);
do
{
i++;
}
while (A[i] < x);
if (i < j)
{
swap(&A[i], &A[j]);
}
else
return j;
}
}
void swap(int *y, int *x)
{
int temp;
temp = *y;
*y = *x;
*x = temp;
}
void printA(int A[], int j, int max)
{
int i;
for (i = j;i < max;i++ )
{
printf("%d ",A[i]);
}
printf("\n");
}