Guest User

Untitled

a guest
Jan 21st, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. int flag=0;
  2.  
  3. void binarysearch(int x, int a[], int m, int n)
  4. {
  5. int middle=(m+n)/2;
  6. if(a[middle]==x)
  7. {
  8. printf("%d has been found at postion %d!n", x, middle+1);
  9. flag=1;
  10. }
  11. else
  12. if(x > a[middle])
  13. binarysearch(x, a, middle, n);
  14. else
  15. if(x < a[middle])
  16. binarysearch(x, a, m, middle);
  17. }
  18.  
  19. main()
  20. {
  21. int i, size, x;
  22. int a[100];
  23. printf("Enter the size of the list : ");
  24. scanf("%d", &size);
  25. printf("Enter the list items in ascending order : n");
  26. for (i=0; i<size; i++)
  27. scanf("%d", &a[i]);
  28. printf("Enter the element to be found : ");
  29. scanf("%d", &x);
  30. binarysearch(x, a, 0, size-1);
  31. if(flag != 1)
  32. printf("%d has not been found in the list!", x);
  33. }
  34.  
  35. if(m == n)
  36. {
  37. if(a[n] == x) { printf("foundn"); }
  38.  
  39. return;
  40. }
  41.  
  42. int binarysearch(int x, int a[], int m, int n)
  43. {
  44. int middle=(m+n)/2;
  45. if(a[middle]==x)
  46. {
  47. printf("%d has been found at postion %d!n", x, middle+1);
  48. return middle;
  49. }
  50. else
  51. if(x > a[middle])
  52. return binarysearch(x, a, middle, n);
  53. else
  54. if(x < a[middle])
  55. return binarysearch(x, a, m, middle);
  56.  
  57. //if it is not found in the whole array
  58. return -1;
  59.  
  60.  
  61. }
  62.  
  63. void binarysearch(int x, int a[], int m, int n)
  64. {
  65. int middle=(m+n)/2;
  66. if(n == m && x != a[middle])
  67. {
  68. printf("%d is not in the array", x);
  69. return;
  70. }
  71. //...
  72.  
  73. void binarysearch(int x, int a[], int m, int n)
  74. {
  75. int middle=(m+n)/2;
  76. if(n == m && x != a[middle])
  77. {
  78. printf("%d is not in the array", x);
  79. }
  80. else
  81. if(a[middle]==x)
  82. //...
Add Comment
Please, Sign In to add comment