Advertisement
Guest User

Untitled

a guest
Oct 24th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <fstream>
  4. long long BinSearch(const int* arr, int count, int key);
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.  
  10. int *array;
  11. int key;
  12. long long result;//добавить бинарный поиск и оставить интерполирующий
  13. fstream in("in1.txt", fstream::in);
  14. if (!in)
  15. return 0;
  16. int num1;
  17. int num;
  18. in >> num1;
  19. array = new int[num1];
  20. int i = 0;
  21. while (!in.eof()) {
  22. in >> num;
  23. array[i] = num;
  24. i++;
  25. }
  26. cout << "Enter a key of search: ";
  27. cin >> key;
  28. result = BinSearch(array, i, key);
  29. int result1 = array[result];
  30. if (result != -1 )
  31. {
  32. for (int g = result; g < num1; g++)
  33. {
  34. if (array[g]>result1)
  35. {
  36. cout <<"next element "<< array[g] << " "<<endl;
  37. break;
  38. }
  39. }
  40. }
  41.  
  42. else
  43. {
  44. for (int g = 0; g < num; g++)
  45. {
  46.  
  47. if (array[g] > key)
  48. {
  49. cout << "next element " << array[g] << " " << endl;
  50. break;
  51. }
  52. }
  53. }
  54. if (result != -1)
  55. cout << "Value is found in an element with an index " << result << endl;
  56. else
  57. //значение не найдено
  58. cout << "Value is not found" << endl;
  59. system("pause");
  60. return 0;
  61. }
  62.  
  63. long long BinSearch(const int* arr, int count, int key)
  64. {
  65. int l = 0; // нижняя граница
  66. int u = count - 1; // верхняя граница
  67.  
  68. while (l <= u) {
  69. long long m = (l + u) / 2;
  70. if (arr[m] == key) return m;
  71. if (arr[m] < key) l = m + 1;
  72. if (arr[m] > key) u = m - 1;
  73. }
  74. return -1;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement