#include<stdio.h>
#include<math.h>
#include<sys/time.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
long int n=100000,a[100000];
void merge(long int begin,long int mid, long int end,long int a[])
{
long int i=begin,j=mid+1,temp[end],cnt=0;
while(cnt<(end-begin+1))
{
if(i==mid+1)
{
temp[cnt++]=a[j];
j++;
}
else if(j==end+1)
{
temp[cnt++]=a[i];
i++;
}
else
{
if(a[i]<a[j])
{
temp[cnt++]=a[i];
i++;
}
else
{
temp[cnt++]=a[j];
j++;
}
}
}
for(i=begin;i<=end;i++)
a[i]=temp[i-begin];
}
void divide(long int a,long int b,long int y[])
{
long int mid=(b-a)/2+a;
if((b-a)>1)
{
divide(a,mid,y);
divide(mid+1,b,y);
}
merge(a,mid,b,y);
}
int main()
{
struct timeval tv1, tv2;
long int mid;
for(long int i=0;i<n;i++)
a[i]=rand();
gettimeofday(&tv1, NULL);
mid=(n-1)/2;
divide(0,mid,a);
divide(mid+1,n-1,a);
merge(0,mid,n-1,a);
gettimeofday(&tv2, NULL);
printf("Time taken in execution = %f micro-seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec));
return 0;
}
#include<math.h>
#include<sys/time.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
long int n=100000,a[100000];
void merge(long int begin,long int mid, long int end,long int a[])
{
long int i=begin,j=mid+1,temp[end],cnt=0;
while(cnt<(end-begin+1))
{
if(i==mid+1)
{
temp[cnt++]=a[j];
j++;
}
else if(j==end+1)
{
temp[cnt++]=a[i];
i++;
}
else
{
if(a[i]<a[j])
{
temp[cnt++]=a[i];
i++;
}
else
{
temp[cnt++]=a[j];
j++;
}
}
}
for(i=begin;i<=end;i++)
a[i]=temp[i-begin];
}
void divide(long int a,long int b,long int y[])
{
long int mid=(b-a)/2+a;
if((b-a)>1)
{
divide(a,mid,y);
divide(mid+1,b,y);
}
merge(a,mid,b,y);
}
int main()
{
struct timeval tv1, tv2;
long int mid;
for(long int i=0;i<n;i++)
a[i]=rand();
gettimeofday(&tv1, NULL);
mid=(n-1)/2;
divide(0,mid,a);
divide(mid+1,n-1,a);
merge(0,mid,n-1,a);
gettimeofday(&tv2, NULL);
printf("Time taken in execution = %f micro-seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec));
return 0;
}
No comments:
Post a Comment