Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //PROGRAM TO DO BINARY SEARCH
- #include <stdio.h>
- int main()
- {
- int size,i,key;
- printf("Enter the size of array: \n");
- scanf("%d",&size);
- int numbers[size];
- printf("Enter the numbers in sorted order: \n");
- for(i=0;i<size;i++)
- {
- printf("\nEnter number %d: ",i+1);
- scanf("%d",&numbers[i]);
- }
- printf("\nEnter the key to search for: ");
- scanf("%d",&key);
- int low=0,high=size;
- while(low<high)
- {
- int mid = (low+high)/2;
- if (numbers[mid] == key)
- {
- printf("The key was found at %d position.",mid+1);
- return 0;
- }
- else if(numbers[mid]<key)
- {
- low = mid+1;
- }
- else if(numbers[mid]>key)
- {
- high = mid-1;
- }
- }
- printf("\nThe key was not found");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement