Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday, 28 April 2019

IOPP Program No.2.A

Program No.2. a)

 Write OpenMP program (for shared memory multiprocessor architecture) to sort the given list of names using Bubble Sort. Display the appropriate environment variables to demonstrate parallel programming.

Solution:
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
#include<string.h>
int main(int argc,char **argv)
{
        int i,j,tid,nthreads,n,chunk=10;
        char name[20][10],t_name[20][10],temp[10];
        printf("Enter how many names to be sorted:\n");
        scanf("%d",&n);
        printf("Enter names one by one :\n");
        for(i=0;i<n;i++) {
                scanf("%s",name[i]);
                strcpy(t_name[i],name[i]);
        }
        #pragma omp parallel shared (name,t_name,temp,nthreads,chunk) private(tid,i,j)
        {
        tid = omp_get_thread_num();
        if(tid==0) {
        nthreads=omp_get_num_threads();
        printf("Starting bubble sort example with %d Threads.\n", nthreads);
        }
        printf("Thread %d starting bubble sort.\n", tid);
        #pragma omp parallel for schedule(static,chunk)
        for(i=0;i<n-1;i++)
        {
                for(j=0;j<n-i-1;j++)
                {
                        if(strcmp(name[j],name[j+1])>0)
                        {
                                strcpy(temp,name[j]);
                                strcpy(name[j],name[j+1]);
                                strcpy(name[j+1],temp);
                        }
                }
        }
        printf("Thread %d ending bubble sort.\n", tid);
        }

        printf("List before Sorting :\n");
        for(i=0;i<n;i++)
                printf("%s\n",t_name[i]);

        printf("List after Sorting :\n");
        for(i=0;i<n;i++)
                printf("%s\n",name[i]);

}

0 comments:

Post a Comment