Advertisement
vencinachev

Hw5-Bobi

Feb 5th, 2021
1,146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. // Упражнение 1: Задачa 2
  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 bubbleSort(int arr[], int n)
  31. {
  32.     int cnt = 0;
  33.     for (int i = 0; i < n-1; i++){
  34.         for (int j = 0; j < n-i-1; j++){
  35.             if (arr[j] > arr[j+1]){
  36.                 swap(arr[j], arr[j+1]);
  37.                 cnt++;
  38.             }
  39.         }
  40.     }
  41.     return cnt;
  42. }
  43.  
  44. int main() {
  45.  
  46.     int nums[SIZE], cpnums[SIZE];
  47.     int n;
  48.     do{
  49.         cout << "Enter number of elements: ";
  50.         cin >> n;
  51.     } while (n <= 0 || n > SIZE);
  52.  
  53.  
  54.     for (int i = 0; i < n; i++){
  55.         cin >> nums[i];
  56.     }
  57.  
  58.     // copy array
  59.     for (int i = 0; i < n; i++){
  60.         cpnums[i] = nums[i];
  61.     }
  62.  
  63.     cout << "Swaps count: " << bubbleSort(cpnums, n) << endl;
  64.  
  65.  
  66.     int m;
  67.     cout << "Enter element for search: ";
  68.     cin >> m;
  69.  
  70.     if(binarySearch(m, cpnums, n) == -1){
  71.         cout << "Not found!" << endl;
  72.     } else {
  73.         cout << m << " is found" << endl;
  74.  
  75.         vector<int> indexes;           // dynamic array (vector)
  76.         for (int i = 0; i < n; i++) {
  77.             if (nums[i] == m){
  78.                 indexes.push_back(i);
  79.             }
  80.         }
  81.         cout << "Indexes: ";
  82.         for (vector<int>::iterator it = indexes.begin() ; it != indexes.end(); ++it){
  83.             cout << *it << ", ";
  84.         }
  85.     }
  86.     return 0;
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement