fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. bool binarySearch (int* array, int arraySize, int element)
  5. {
  6. if ( arraySize == 0 )
  7. {
  8. return false;
  9. }
  10.  
  11. int startPos = 0;
  12. int endPos = arraySize;
  13. while ( true )
  14. {
  15. int spanSize = endPos - startPos;
  16. if ( spanSize == 1 )
  17. {
  18. break;
  19. }
  20. int pivotPos = startPos + (spanSize >> 1);
  21. if ( element < array[pivotPos] )
  22. {
  23. // go left
  24. endPos = pivotPos;
  25. }
  26. else
  27. {
  28. // go right
  29. startPos = pivotPos;
  30. }
  31. }
  32. return element == array[startPos];
  33. }
  34.  
  35. int main()
  36. {
  37. int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  38. cout << (binarySearch(array, 10, 0) ? "Found." : "Not found.");
  39. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
Found.