fork(2) download
  1. int BinarySearch(int arr[], int len, int target) {
  2. int first = 0;
  3. int last = len-1;
  4. int mid;
  5. while ((first < last) && (arr[mid]!=target))
  6. {
  7. // Assert: Array is sorted and first <= last
  8. //Initialization:target is within (extremes inclusive) the range of first and last. IE First<=x<=Last
  9. mid = (first+last) / 2;
  10. printf("mid: %d \n",mid);
  11. //Maintenance: Increasing first to mid+1 if x>mid or decrease last to min-1 if x<mid.
  12. if (target < arr[mid])
  13. {last = mid-1;
  14. printf("last: %d \n",last);
  15. }
  16. else
  17. {first = mid+1;
  18. printf("first: %d \n",first);
  19. }
  20. }
  21. //Termination: target is not within the array.
  22. if ((first==last) && (arr[first]==target)) return 1;
  23. else return -1;
  24.  
  25. }
  26.  
  27. int main(){
  28. int arr[10]={1,2,3,4,5,6,7,8,9,10};
  29. int target=5;
  30. int len=10;
  31.  
  32. printf("%d \n",BinarySearch( arr, len, target));
  33. }
Success #stdin #stdout 0s 2160KB
stdin
Standard input is empty
stdout
mid: 4 
first: 5 
-1