-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.cpp
75 lines (69 loc) · 1007 Bytes
/
merge_sort.cpp
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
#include <bits/stdc++.h>
using namespace std;
void merge(int a[], int lb, int mid, int ub)
{
int i = lb;
int j = mid + 1;
int k = 0;
int b[20], m, n;
while (i <= mid && j <= ub)
{
if (a[i] <= a[j])
{
b[k] = a[i];
i++; k++;
}
else
{
b[k] = a[j];
j++; k++;
}
}
if (i > mid)
{
while (j <= ub)
{
b[k] = a[j];
j++; k++;
}
}
else
{
while (i <= mid)
{
b[k] = a[i];
k++; i++;
}
}
for (i = lb; i <= ub; i++)
{
a[i] = b[i - lb];
}
}
void mergeshort(int a[], int lb, int ub)
{
if (lb < ub)
{
int mid = (lb + ub) / 2;
mergeshort(a, lb, mid);
mergeshort(a, mid + 1, ub);
merge(a, lb, mid, ub);
}
}
int main()
{
int a[10], n;
printf("how much element you want to sort");
scanf("%d", &n);
int i;
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
mergeshort(a, 0, n - 1);
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}