-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmergesort_b.c
80 lines (61 loc) · 1.5 KB
/
mergesort_b.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
#include <stdio.h>
int array[100];
int num;
void Combine(int arr[], int left[], int right[], int totalsize, int leftsize, int rightsize)
{
int k = 0; // <===for left
int l = 0; // <===for right
int m = 0; // <===for main array
while(k < leftsize && l < rightsize) {
if (left[k] <= right[l]) {
arr[m] = left[k];
k++;
m++;
} else if (left[k] >= right[l]) {
arr[m] = right[l];
l++;
m++;
}
}
while(m < totalsize && k != leftsize) {
arr[m] = left[k];
m++;
k++;
}
while(m < totalsize && l != rightsize) {
arr[m] = right[l];
m++;
l++;
}
}
void MergeSort(int arr[], int sizeofarr)
{
if (sizeofarr == 1)
return;
int k, l;
int mid = sizeofarr/2;
/* Create two auxillary arrays */
int left[mid];
int right[sizeofarr - mid];
/*Fill left array */
for(k=0; k < mid;k++)
left[k] = arr[k];
/*Fill left array */
for(k=mid, l=0; k < sizeofarr; k++, l++)
right[l] = arr[k];
MergeSort(left, mid);
MergeSort(right, sizeofarr - mid);
Combine(arr, left, right, sizeofarr, mid, sizeofarr-mid);
}
int main()
{
int k;
printf("Welcome to Merge sorting..\n");
printf("Enter numbver of elements,,\n");
scanf("%d", &num);
for(k=0; k < num; k++)
scanf("%d", &array[k]);
MergeSort(array, num);
for(k=0; k < num; k++)
printf("[%d]", array[k]);
}