fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void search( int a[], int array_length, int key) {
  5. int high = array_length -1;
  6. int low = 0;
  7. if (a[low] > key ) {
  8. cout << "Key not Found. Possible Insertion before : " << a[low] << endl;
  9. return;
  10. }
  11. else if (a[high] < key ) {
  12. cout << "Key not Found. Possible Insertion after : " << a[high] << endl;
  13. return;
  14. }
  15. else {
  16. bool present=false;
  17. int mid = 0;
  18. while ( low <= high ) {
  19. mid = low + ((high - low) / 2);
  20. present = false;
  21. if (a[mid] > key){
  22. high = mid-1;
  23. } else if (a[mid] < key){
  24. low = mid+1;
  25. }else {
  26. present = true;
  27. break;
  28. }
  29. }
  30. if (present) cout << "Key Found at index : " << mid << endl;
  31. else {
  32. if (a[mid] < key )
  33. cout << "Key not Found. Possible Insertion after : " << a[mid] << endl;
  34. else
  35. cout << "Key not Found. Possible Insertion before : " << a[mid] << endl;
  36. }
  37. }
  38. }
  39. int main() {
  40. int a[] = {2, 5 , 8, 13, 18, 22, 28, 31, 35, 38, 40};
  41. int array_length = sizeof(a) / sizeof(a[0]);
  42. search(a,array_length, 15);
  43. return 0;
  44. }
Success #stdin #stdout 0s 2684KB
stdin
Standard input is empty
stdout
Key not Found. Possible Insertion before : 18