Binary search in C

Binary search in C


Binary Search:

  • in computer science, binary search, also known as half-interval search, logarithmic search, or binarychop, is a search algorithm that finds the position of a target value within a sorted array.
  • It necessary that given data is sorted in ascending order or descending order.
  • below is the program of binary search for ascending ordered data.

PROGRAM :

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int n,int a[10])
  5. {
  6. int i,mid,key,ub,lb;
  7. printf("How many numbers you wants to enter=");
  8. scanf("%d",&n);
  9.  
  10. lb=0;
  11. ub=n-1;
  12.  
  13. printf("\n%d elements are=",n);
  14.  
  15. for(i=0;i<n;i++){
  16. printf("\na[%d]=",i);
  17. scanf("%d",&a[i]);
  18. }
  19. printf("\nKey=",n);
  20. scanf("%d",&key);
  21.  
  22. mid=(lb+ub)/2;
  23.  
  24. while(a[mid]!=key && lb<=ub){
  25. if(key<a[mid]){
  26. ub=mid-1;
  27. }
  28. else{
  29. lb=mid+1;
  30. }
  31. mid=(lb+ub)/2;
  32. }
  33.  
  34. if(a[mid]==key){
  35. printf("\nNumber has found");
  36. printf("\nPosition of number is %d",mid+1);
  37. }
  38. else{
  39. printf("Number hasn't found");
  40. }
  41. return 0;
  42. }

OUTPUT:

How many numbers you wants to enter=5

5 elements are=
a[0]=12

a[1]=45

a[2]=56

a[3]=89

a[4]=90

Key=89

Number has found
Position of number is 4


Comments

Popular posts from this blog

Introduction to ChatGPT: Explain what ChatGPT is, how it works, and what it is used for.

Multi Level Inheritance In cpp

Hybrid Inheritance In cpp