9/22/13 CAPE Computer Science Unit 2 - LiveBinder A fast way to search a sorted array is to use abinary search. The idea is to look at the element in the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half. Pseudocode: BinarySearch(array, size, key) BEGIN low = 0 high = size while (low + 1 < high) test = (low + high)/2 if (array[test] > key) high = test else low = test endwhile if (array[low] = = key return low else www.livebinders.com/play/play?id=127326 1/3 9/22/13 CAPE Computer Science Unit 2 - LiveBinder return -1 END C Program: 1. #include<stdio.h> 2. #include<conio.h> 3. void main() 4. { 5. int a[10],n,i; 6. int low,high,mid,key; 7. clrscr(); 8. printf(“enter the total numbers:"); 9. scanf(“%d",&n); 10. printf(“enter the array elements in ascending or descending order:" ); 11. for(i=0;i<n;i++) 12. scanf(“%d",&a[i]); 13. 14. low=0; 15. high=9; 16. mid=(low+high)/2; 17. printf(“\nenter the number to be searched:"); 18. scanf(“%d",&key); 19. while(low<=high && a[mid]!=key) 20. { 21. if(key<a[mid]) 22. high=mid-1; 23. else 24. low=mid+1; 25. mid=(low+high)/2; 26. } 27. If(a[mid]==key) 28. { www.livebinders.com/play/play?id=127326 2/3 9/22/13 CAPE Computer Science Unit 2 - LiveBinder 29. printf(“\nthe number is found at position -",mid); 30. } 31. else 32. { 33. printf(“\nthe number is not found"); 34. } 35. getch(); 36. } www.livebinders.com/play/play?id=127326 3/3