Binary Search using User Defined Function !!
#include <stdio.h>
void inp(int arr[50],int n){
int i;
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
}
void show(int arr[50],int n){
int i;
for(i=0;i<n;i++){
printf("a[%d] = %d\n",i,arr[i]);
}
}
void sort(int a[50],int n){
int i,j,temp;
for(i=0;i<n;i++){
for(j=0;j<n-1;j++){
if(a[j]>a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
//show(arr);
}
}
void binsearch(int a[50],int n,int s){
int l = 0,r = n -1,mid;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == s){
printf("Element Found in %d Position",mid);
break;
}else if(a[mid]<s){
l = mid + 1;
//Mashrafe004
}else{
r = mid - 1;
}
}
if(l>r){
printf("Element not found!");
}
}
void main (){
int n,s;
printf("enter the range : \n");
scanf("%d",&n);
int a[n];
printf("Enter the Array : \n");
inp(a,n);
printf("Array Before Sorting :\n");
show(a,n);
sort(a,n);
printf("Array after sorting :\n");
show(a,n);
printf("Enter the number searching : \n");
scanf("%d",&s);
binsearch(a,n,s);
}
Comments
Post a Comment