Advertisement
kxcoze

tanya_request

Mar 25th, 2020
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>  
  3. #include <conio.h>
  4.  
  5. using namespace std;
  6.  
  7. void generator(int* mass, int n);
  8. void print(int* mass, int n);
  9. int linSearch(int* mass, int y, int z);
  10. void BubbleSort(int* mass, int n);
  11. int BinSearch(int* mass, int n, int k);
  12.  
  13. int main() {
  14.     srand(time(NULL));
  15.     setlocale(LC_ALL, "Rus");
  16.     const int n = 20;
  17.     int A[n], x, c, nElement = 0;
  18.  
  19.     generator(A, n);
  20.     print(A, n);
  21.  
  22.     cout << "Искомое число: ";
  23.     cin >> x;
  24.     nElement = linSearch(A, n, x);
  25.     if (nElement != -1) cout << "Число " << x << " находится в ячейке с индексом: " << nElement << endl;
  26.     else cout << "В массиве нет такого значения" << endl;
  27.  
  28.     BubbleSort(A, n);
  29.     cout << "\nОтсортированный массив:" << endl;
  30.     print(A, n);
  31.  
  32.     cout << "\nИскомое число: ";
  33.     cin >> c;
  34.     nElement = BinSearch(A, n, c);
  35.     if (nElement != -1) cout << "Число " << c << " находится в ячейке с индексом: " << nElement << endl;
  36.     else cout << "В массиве нет такого значения" << endl;
  37.  
  38.     _getch();
  39.     return 0;
  40. }
  41.  
  42.  
  43. void generator(int* mass, int n) {
  44.     for (int i = 0; i < n; i++)
  45.         mass[i] = rand() % 101 - 50;
  46. }
  47.        
  48. void print(int* mass, int n) {  
  49.     cout << '{';
  50.     for (int i = 0; i < n; i++) {
  51.         if (i != n-1)
  52.             cout << mass[i] << ", ";
  53.         else
  54.             cout << mass[i];
  55.     }
  56.     cout << "}\n";
  57. }
  58.  
  59.  
  60. int linSearch(int* mass, int z, int y) {
  61.     for (int i = 0; i < z; i++) {
  62.         if (mass[i] == y) return i;
  63.     }
  64.     return -1;
  65. }
  66.  
  67. void BubbleSort(int* mass, int n) {
  68.     for (int i = 0; i < n - 1; i++) {
  69.         for (int j = 0; j < n - i - 1; j++) {
  70.             if (mass[j] > mass[j + 1]) {
  71.                 int t = mass[j];
  72.                 mass[j] = mass[j + 1];
  73.                 mass[j + 1] = t;
  74.             }
  75.         }
  76.     }
  77. }
  78.  
  79. int BinSearch(int* mass, int n, int k) {
  80.     int L = 0, R = n - 1, m;
  81.  
  82.     while (L < R) {
  83.         m = (L + R) / 2;
  84.         k > mass[m] ? L = m + 1 : R = m;
  85.     }
  86.     if (k == mass[L]) return L;
  87.     return -1;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement