-
Notifications
You must be signed in to change notification settings - Fork 0
/
C_Merge_sort.c
97 lines (76 loc) · 1.32 KB
/
C_Merge_sort.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
/* not in place sort
* Better than bubble, selection and insertion as time complexity is (n logn)
* Logic is, recursive, divide and sort
*/
#include <stdio.h>
#include <string.h>
int input_set[5];
int temp[5];
void PrintSet(int * arr, int len)
{
int i;
for(i=0 ; i<len; i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
}
void merge(int arr[], int b, int m, int e)
{
int i, j, k;
for(i=b, j=m+1, k=b; i<=m && j<=e; k++)
{
if(arr[i] <= arr[j])
{
temp[k] = arr[i];
i++;
}
else
{
temp[k] = arr[j];
j++;
}
}
while(i<=m)
{
temp[k]=arr[i];
k++;
i++;
}
while(j<=e)
{
temp[k] = arr[j];
k++;
j++;
}
for(i=b; i<=e ; i++)
arr[i] = temp[i];
PrintSet(temp,5);
}
void mergesort(int * in_set, int begin_index, int end_index)
{
if( begin_index < end_index )
{
int mid_index = (begin_index + end_index)/2;
mergesort(in_set, begin_index, mid_index);
mergesort(in_set, mid_index+1, end_index);
merge(in_set, begin_index, mid_index, end_index);
}
}
int main()
{
int i, len;
printf("Input numbers: \n");
len = sizeof(input_set)/sizeof(int);
for(i=0; i<len; i++)
{
scanf("%d",&input_set[i]);
}
printf("Unsorted Array : ");
PrintSet(input_set, len);
memset(temp,0,len);
mergesort(input_set, 0, len-1);
printf("Sorted Array : ");
PrintSet(input_set, len);
return 0;
}