-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormal_merge_sort.cpp
More file actions
119 lines (99 loc) · 2.02 KB
/
normal_merge_sort.cpp
File metadata and controls
119 lines (99 loc) · 2.02 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
#include<stdio.h>
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<sstream>
#include<time.h>
#define MAX 50000
using namespace std;
void mergeSort(int arr[],int low,int mid,int high);
void partition(int arr[],int low,int high);
int main()
{
double time_spent;
clock_t begin,end;
int merge[MAX],i,n,index=0;
FILE* file = fopen ("data.txt", "r");
int x = 0,count=0;
fscanf (file, "%d", &x);
while (!feof (file))
{
merge[index]=x;
index++;
fscanf (file, "%d", &x);
}
printf("\nCount: %d\n",index);
fclose(file);
n=index;
begin=clock();
partition(merge,0,n-1);
end=clock();
time_spent=(double)(end-begin)/CLOCKS_PER_SEC;
printf("\nThe difference is: %f seconds\n",time_spent);
FILE *f;
f = fopen("output_normal_merge_sort.txt", "w");
printf("After merge sorting elements saved to output_normal_merge_sort.txt ");
for(i=0; i<n; i++)
{
fprintf(f,"%d\n",merge[i]);
}
fclose(f);
FILE *fp;
fp = fopen("time_normal_merge_sort.txt", "w");
fprintf(fp, "%f", time_spent);
fclose(fp);
getchar();
return 0;
}
void partition(int arr[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
partition(arr,low,mid);
partition(arr,mid+1,high);
mergeSort(arr,low,mid,high);
}
}
void mergeSort(int arr[],int low,int mid,int high)
{
int i,m,k,l,temp[MAX];
l=low;
i=low;
m=mid+1;
while((l<=mid)&&(m<=high))
{
if(arr[l]<=arr[m])
{
temp[i]=arr[l];
l++;
}
else
{
temp[i]=arr[m];
m++;
}
i++;
}
if(l>mid)
{
for(k=m; k<=high; k++)
{
temp[i]=arr[k];
i++;
}
}
else
{
for(k=l; k<=mid; k++)
{
temp[i]=arr[k];
i++;
}
}
for(k=low; k<=high; k++)
{
arr[k]=temp[k];
}
}