Blogger news

Followers

Monday, July 21, 2014
/*Using OpenMP,implements a parallelized Merge Sort algorithm to sort a given set of elements and determine
The time required to sort the elements,Repeat the experiment for different values of n,the number of elements
In the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or
Can be generated using the random number generator*/


#include<stdio.h>
#include<time.h>
#include<omp.h>
int a[50000],b[50000];
void mergesort(int,int);
void merge(int,int,int);
void merge(int low,int mid,int high)
{
            int i,j,k,h,m;
            h=low;j=mid+1;i=low;
            while(h<=mid && j<=high)
            {
                        usleep(100);
                        if(a[h]<a[j])
                        {
                                    b[i]=a[h];
                                    h++;
                        }
                        else
                        {
                                    b[i]=a[j];
                                    j++;
                        }
                        i++;
            }
            if(h>mid)
            {
                        for(k=j;k<=high;k++)
                        {
                                    b[i]=a[k];
                                    i++;
                        }
            }
            else
            {
                        for(k=h;k<=mid;k++)
                        {
                                    b[i]=a[k];
                                    i++;
                        }
            }
            for(k=low;k<=high;k++)
                        a[k]=b[k];
}
void mergesort(int low,int high)
{
            int mid;
            if(low<high)
            {
                        mid=(low+high)/2;
                        #pragma omp parallel sections
                        {
                                    #pragma omp section
                                                mergesort(low,mid);
                                    #pragma omp section
                                                mergesort(mid+1,high);
                        }
                        merge(low,mid,high);
            }
}
void main()
{
            int n,i,k;
            double start=0,end=0,dur;
            omp_set_num_threads(4);
            printf("\nEnter the number of inputs\n");  
            scanf("%d",&n);
            a[n]=9999;
            for(i=0;i<n;i++)
                        a[i]=rand()%100;
            printf("\nRandom numbers are:\n\n");
            for(i=0;i<n;i++)
                        printf("\t%d",a[i]);
            printf("\n");
            start=clock();
            mergesort(0,n-1);
            end=clock();
            dur=(end-start)/CLOCKS_PER_SEC;
            printf("\nTime taken is:%lf\t\n",dur);
            printf("The sorted array is:");
            for(k=0;k<n;k++)
                        printf("%d\t",a[k]);
}


0 comments: