This repository was archived by the owner on May 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise9.c
More file actions
149 lines (110 loc) · 2.12 KB
/
Copy pathexercise9.c
File metadata and controls
149 lines (110 loc) · 2.12 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#ifdef Exer9
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#define SWAP(a, b) a ^= b ^= a ^= b
#define SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t))
int partition(int list[], int left, int right)
{
int pivot ,temp;
int low, high;
low = left;
high = right + 1;
pivot = list[left];
do
{
do
low++;
while(low <= right && list[low] < pivot);
do
high--;
while (high >= left && list[high] > pivot);
if (low < high)
SWAP(list[low], list[high],temp);
}
while(low < high);
SWAP(list[left], list[high], temp);
return high;
}
void quicksort(int list[], int left, int right)
{
if (left < right)
{
int q = partition(list, left, right);
quicksort(list, left, q - 1);
quicksort(list, q + 1, right);
}
}
void merge(int list[], int left, int mid, int right);
void mergesort(int list[], int left, int right)
{
int mid;
if (left < right)
{
mid = (left + right)/ 2;
mergesort(list, left, mid);
mergesort(list, mid + 1, right);
merge(list, left, mid, right);
}
return;
}
void merge(int list[], int left, int mid, int right)
{
int* out;
int indexL, indexR, indexO;
indexL = left;
indexR = mid + 1;
indexO = 0;
out = (int*)malloc(sizeof(int) * (right - left + 1));
while (indexL <= mid && indexR <= right)
{
if (list[indexL] < list[indexR])
{
out[indexO] = list[indexL];
indexO++;
indexL++;
}
else
{
out[indexO] = list[indexR];
indexR++;
indexO++;
}
}
if (indexL > mid)
{
memcpy(out + indexO, list + indexR, sizeof(int) * (right - indexR + 1));
}
else
{
memcpy(out + indexO, list + indexL, sizeof(int) * (mid - indexL + 1));
}
memcpy(list + left, out, sizeof(int) * (right - left + 1));
free(out);
}
void display(int list[], int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("%d, ", list[i]);
}
printf("\n");
}
int main()
{
int n = 9;
int listA[] = {5,3,8,4,9,1,6,2,7};
int listB[] = {5,3,8,4,9,1,6,2,7};
printf("merge sort : \n");
display(listA, n);
mergesort(listA, 0, n -1);
display(listA, n);
printf("quick sort : \n");
display(listB, n);
quicksort(listB, 0, n -1);
display(listB, n);
return 0;
}
//
#endif