fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. const int SIZE = 4;
  6. const int NOT_FOUND = -1;
  7. int binarySearch(int mat[][SIZE], int &line , int num);
  8. int main()
  9. {
  10. int num, index, mat[SIZE][SIZE] = { 0,1,5,2,
  11. 8,6,7,7,
  12. 11,7,7,10,
  13. 11,12,9,11 };
  14. int line = sizeof(mat) / sizeof(mat[0][0]);
  15. cout << "please type a number to search: " << endl;
  16. cin >> num;
  17. index = binarySearch(mat, line, num);
  18. if (index == NOT_FOUND)
  19. cout << "The value: " << num << "doesn't exist in the array\n";
  20. else
  21. cout << "The value: " << num << " exists in line " << line+1 <<" and column: " << index+1 << endl;
  22. return 0;
  23. }
  24.  
  25.  
  26. int binarySearch(int mat[][SIZE], int &line, int num)
  27. {
  28. int j;
  29. for (j = 0; j < SIZE; j++)
  30. {
  31. int low = 0, high = SIZE - 1, middle;
  32. while (low <= high)
  33. {
  34. middle = (low + high) / 2;
  35. if (num == mat[middle][j])
  36. {
  37. line = middle;
  38. return j;
  39. }
  40. else if (num < mat[middle][j])
  41. high = middle - 1;
  42. else
  43. low = middle + 1;
  44. }
  45. }
  46. return NOT_FOUND;
  47. }
Success #stdin #stdout 0s 3460KB
stdin
10
stdout
please type a number to search: 
The value: 10 exists in line 3 and column: 4