-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathExercise-2-1.quicksort-iteratively.c
129 lines (104 loc) · 2.3 KB
/
Exercise-2-1.quicksort-iteratively.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
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
#include <stdio.h>
#include <stdlib.h>
#define LENGTH_OF_ARRAY(array) (sizeof(array) / sizeof(array[0]))
#define Error(Str) FatalError(Str)
#define FatalError(Str) fprintf(stderr, "%s\n", Str), exit(1)
#define ElementType int
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
struct Node
{
ElementType element;
PtrToNode next;
};
int isEmpty(Stack s)
{
return s->next == NULL;
}
void push(ElementType x, Stack s)
{
PtrToNode newCell;
newCell = malloc(sizeof(struct Node));
if (newCell == NULL)
Error("Must use createStack first");
else
{
newCell->element = x;
newCell->next = s->next;
s->next = newCell;
}
}
void pop(Stack s)
{
PtrToNode FirstCell;
if (isEmpty(s))
Error("Empty Stack");
else
{
FirstCell = s->next;
s->next = s->next->next;
free(FirstCell);
}
}
void makeEmpty(Stack s)
{
if (s == NULL)
Error("Must use createStack first");
else
while (!isEmpty(s))
pop(s);
}
Stack createStack()
{
Stack s;
s = malloc(sizeof(struct Node));
if (s == NULL)
FatalError("Out of Memory!!!");
s->next = NULL;
makeEmpty(s);
return s;
}
/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
/* quicksort iteratively: sort v[0]..v[n-1] into increasing order */
void quicksortiter(int v[], int n)
{
Stack s = createStack();
int left = 0, right = n;
push(left, s);
push(right, s);
while (!isEmpty(s))
{
right = s->next->element;
pop(s);
left = s->next->element;
pop(s);
if (left >= right)
continue;
swap(v, left, rand() % (right - left) + left);
int pivot = left;
for (int i = left + 1; i < right; i++)
if (v[i] < v[left])
swap(v, ++pivot, i);
swap(v, left, pivot);
push(left, s);
push(pivot, s);
push(pivot + 1, s);
push(right, s);
}
}
int main(int argc, char const *argv[])
{
int arr[10] = {3, 4, 2, 1, 5, 6, 0, 2, 10, 7};
quicksortiter(arr, LENGTH_OF_ARRAY(arr));
for (size_t i = 0; i < LENGTH_OF_ARRAY(arr); i++)
printf("%d ", arr[i]);
return 0;
}