Binary Search


SUBMITTED BY: Neutrino

DATE: Dec. 9, 2020, 3:06 a.m.

FORMAT: Text only

SIZE: 1.5 kB

HITS: 692

  1. #include <stdio.h>
  2. #define size 10
  3. int smallest(int arr[],int k,int n);
  4. void selection_sort(int arr[], int n);
  5. int main(void)
  6. {
  7. int arr[size];
  8. int i,n,num,beg,end,mid,found=0;
  9. printf("\n Enter the no of elements in the array ");
  10. scanf("%d",&n);
  11. printf("\n Enter the elements :");
  12. for (i=0;i<n;i++)
  13. {scanf("%d",&arr[i]);}
  14. selection_sort(arr,n);
  15. printf("\n The sorted array is :");
  16. for(i=0;i<n;i++)
  17. {
  18. printf(" %d\t",arr[i]);
  19. }
  20. printf("\n\n Enter the element that has to be searched ");
  21. scanf("%d",&num);
  22. beg=0,end=n-1;
  23. while (beg<=end)
  24. {
  25. mid= (beg+end)/2;
  26. if(arr[mid]==num)
  27. {
  28. printf("\n %d is present in the array at position %d",num,mid+1);
  29. found=1;
  30. break;
  31. }
  32. else if(arr[mid]>num)
  33. end=mid-1;
  34. else
  35. beg=mid+1;
  36. }
  37. if (beg >end && found==0)
  38. printf("\n %d does not exist in the array ");
  39. return 0;
  40. }
  41. int smallest(int arr[],int k, int n)
  42. {
  43. int pos= k, small=arr[k],i;
  44. for(i=k+1;i<n;i++)
  45. {
  46. if(arr[i]<small)
  47. {
  48. small=arr[i];
  49. pos=i;
  50. }
  51. }
  52. return pos;
  53. }
  54. void selection_sort(int arr[],int n)
  55. {
  56. int k, pos,temp;
  57. for(k=0;k<n;k++)
  58. {
  59. pos =smallest(arr,k,n);
  60. temp=arr[k];
  61. arr[k]=arr[pos];
  62. arr[pos ]=temp;
  63. }
  64. }

comments powered by Disqus