-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_Sort.c
108 lines (94 loc) · 1.63 KB
/
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
97
98
99
100
101
102
103
104
105
106
107
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int num=0;
int *A;
int *temp;
int i, t;
void MergeSort(int arr[],int length)
{
A=(int*)malloc(length*sizeof(int));
temp=(int*)malloc(length*sizeof(int));
for(i=0;i<length;i++)
{
A[i]=arr[i];
temp[i]=arr[i];
}
//printf("here " );
}
void merge(int start,int mid,int end)
{
int k;
int i=start;
int j=mid+1;
for(t=start;t<=end;t++)
{
temp[t]=A[t];
}
for(k=start;k<=end;k++)
{
if(i>mid){
A[k]=temp[j++];
}
else if(j>end){
A[k]=temp[i++];
}
else if(temp[i]<temp[j]){
A[k]=temp[i++];
}
else{
A[k]=temp[j++];
}
}
}
void display()
{
for(i=0;i<=num;i++){
printf("%d ",A[i]);
}
}
void sort(int start, int end)
{
int mid;
if(start<end)
{
mid=(start+end)/2;
sort(start,mid);
sort(mid+1,end);
merge(start,mid,end);
}
}
int main()
{
clock_t begin, end;
double total_t;
begin = clock();
int i;
num=0;
//int array[]={2,4,6,8,1,0,-5};
FILE *filepointer;
filepointer=fopen("1-25000.txt","r");
fscanf(filepointer, "%d",&num);
int *array=malloc(num*sizeof(int));
//int n=num;
for(i=0;i<=num;i++){
fscanf(filepointer,"%d",&array[i]);
}
// printf("list before sorting \n");
// for(i=0;i<=num;i++)
// {
// printf("%d\n",array[i]);
// }
MergeSort(array,num);
sort(0,num);
printf("\n list after sorting\n");
display();
free(array);
end= clock();
total_t = (double)(end - begin );
//printf("Total numbers sorted: %d \n",num);
printf("\nInitial time taken by CPU: %d \n", begin );
printf("End time taken by CPU: %d \n", end );
printf("Total time taken by CPU: %f seconds\n", total_t );
return 0;
}