Wednesday, 16 March 2016

Implement n-ary search algorithm using OPENMP

Implement n-ary search algorithm using OPENMP

 

#include<stdio.h>
#include<omp.h>
int e,n;
int newarr[100];

int nary(int arr[],int s);

int main(){
const int s;
printf("Enter the size of the array u wish :");
scanf("%d",&s);
printf("Enter the array in ascending order : \n");
int arr[s];
int i=0;
for(i=0; i < s;i++)
scanf("%d",&arr[i]);
                                                    
printf("Enter the element to be searched: \n");
scanf("%d",&e);
X:
printf("Enter the value of n :");
scanf("%d",&n);
if(n > s)
{
printf("Value of n exceeds size of array!\n");
goto X;
}
int ans=nary(arr,s);
if(ans==0)
printf("Value not found in the given array.\n");
else
printf("The value has been successfully found !\n");
return 0;
}

int nary(int arr[],int s)
{
if(arr[0]==e)
return 1;

if(s/n==0)
return 0;
#pragma omp parallel num_threads(n)
{
int tid= omp_get_thread_num();
int t=0,k=0,i=0;
 for(i=0; i < s; i=i+(s/n))
  if(t==tid && (arr[i] < =e && arr[(i+s/n)-1] > =e))//allotting nodes to different threads & if value lies in the given thread set.
   for(k=0; k < (s/n);k++) 
    newarr[k]=arr[k+i];//extract the thread set elements.    
 t++;
}
nary(newarr,s/n);//recursive call to the function 
}

---------OUTPUT-------------

Output--

[estudymoney@localhost ~]$ gcc -o finalnary -fopenmp finalnary.c
[estudymoney@localhost ~]$ ./finalnary
Enter the size of the array u wish :9
Enter the array in ascending order : 
1
2
3
4
5
6
7
8
9
Enter the element to be searched: 
8
Enter the value of n :3
The value has been successfully found !

No comments:

Post a Comment