forked from yunghsianglu/CProgramExercise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.c
More file actions
130 lines (120 loc) · 2.35 KB
/
Copy pathquicksort.c
File metadata and controls
130 lines (120 loc) · 2.35 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define RANGE 10000
int * arrGen(int size);
// generate a sorted array of integers
void swap(int * a, int * b);
static void quickSortHelp(int * arr, int first, int last)
{
// [first, last]: range of valid indexes (not last - 1)
if (first >= last) // unnecessary to sort one or no element
{
return;
}
#ifdef DEBUG
printf("first = %d, last = %d\n", first, last);
#endif
int pivot = arr[first];
int low = first + 1;
int high = last;
while (low < high)
{
while ((low < last) && (arr[low] <= pivot))
{
// <= so that low will increment when arr[low] is the same
// as pivot
// using < will stop incrementing low when arr[low] is the
// same as pivot and the outer while loop will not stop
low ++;
}
while ((first < high) && (arr[high] > pivot))
{
high --;
}
if (low < high)
{
swap (& arr[low], & arr[high]);
}
}
if (pivot > arr[high])
{
swap(& arr[first], & arr[high]);
}
quickSortHelp(arr, first, high - 1);
quickSortHelp(arr, low, last);
}
void quickSort(int * arr, int len)
{
quickSortHelp(arr, 0, len - 1);
}
void printArray(int * arr, int len);
int main(int argc, char * * argv)
{
if (argc < 2)
{
printf("need a positive integer\n");
return EXIT_FAILURE;
}
if (argc == 3)
{
srand(strtol(argv[2], NULL, 10));
}
else
{
srand(time(NULL)); // set the seed
}
int num = strtol(argv[1], NULL, 10);
if (num <= 0)
{
printf("need a positive integer\n");
return EXIT_FAILURE;
}
int * arr = arrGen(num);
printArray(arr, num);
quickSort(arr, num);
printArray(arr, num);
free (arr);
return EXIT_SUCCESS;
}
void swap(int * a, int * b)
{
int s = * a;
* a = * b;
* b = s;
}
int * arrGen(int size)
{
if (size <= 0)
{
return NULL;
}
int * arr = malloc(sizeof(int) * size);
if (arr == NULL)
{
return NULL;
}
int ind;
for (ind = 0; ind < size; ind ++)
{
arr[ind] = rand() % RANGE;
}
return arr;
}
void printArray(int * arr, int len)
{
int ind;
int sorted = 1;
for (ind = 0; ind < len; ind ++)
{
#ifdef DEBUG
printf("%d ", arr[ind]);
#endif
if ((ind > 0) && (arr[ind] < arr[ind -1]))
{
sorted = 0;
}
}
printf("\nsorted = %d\n\n", sorted);
}