Advertisement
vencinachev

Hw4-Bobi

Feb 5th, 2021
1,116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. // Упражнение 1: Задачa 1
  2. #include <iostream>
  3. #include <vector>
  4. #define SIZE 200
  5.  
  6. using namespace std;
  7.  
  8. int binarySearch( int searchElement, int data[], int length)
  9. {
  10.     int low = 0;
  11.     int high = length - 1;
  12.     int middle = ( low + high + 1 ) / 2;
  13.     int location = -1;
  14.     do {
  15.         if ( searchElement == data[ middle ] ){
  16.            location = middle;
  17.         }
  18.         else if ( searchElement < data[ middle ] ) {
  19.             high = middle - 1;
  20.         }
  21.         else {
  22.             low = middle + 1;
  23.         }
  24.  
  25.         middle = ( low + high + 1 ) / 2;
  26.      }  while ( ( low <= high ) && ( location == -1 ) );
  27.      return location;
  28. }
  29.  
  30. int main() {
  31.  
  32.     int nums[SIZE];
  33.     int n;
  34.     do
  35.     {
  36.         cout << "Enter number of elements: ";
  37.         cin >> n;
  38.     }
  39.     while (n <= 0 || n > SIZE);
  40.  
  41.     for (int i = 0; i < n; i++)
  42.     {
  43.         cin >> nums[i];
  44.     }
  45.  
  46.     int m;
  47.     cout << "Enter element for search: ";
  48.     cin >> m;
  49.  
  50.     if(binarySearch(m, nums, n) == -1){
  51.         cout << "Not found!" << endl;
  52.     } else {
  53.         cout << m << " is found" << endl;
  54.  
  55.         vector<int> indexes;           // dynamic array (vector)
  56.         for (int i = 0; i < n; i++) {
  57.             if (nums[i] == m){
  58.                 indexes.push_back(i);
  59.             }
  60.         }
  61.         cout << "Indexes: ";
  62.         for (vector<int>::iterator it = indexes.begin() ; it != indexes.end(); ++it){
  63.             cout << *it << ", ";
  64.         }
  65.     }
  66.     return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement