Advertisement
kxcoze

lab22_9_1

Sep 7th, 2020
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>
  3.  
  4. using namespace std;
  5.  
  6. const int N = 20;
  7.  
  8. void input(int *arr, int n);
  9. void print(int *arr, int n);
  10. void input_sort(int *arr, int n);
  11. bool bin_srch(int *arr, int n, int t);
  12. bool line_srch(int *arr, int n, int t);
  13.  
  14. int main() {
  15.     setlocale(LC_ALL, "rus");
  16.     srand(time(NULL));
  17.     int arr[N], k;
  18.     input(arr, N);
  19.     cout << "Исходный массив: " << endl;
  20.     print(arr, N);
  21.  
  22.     cout << "Введите искомый элемент: ";
  23.     cin >> k;
  24.     if (line_srch(arr, N, k))
  25.         cout << "Элемент найден!" << endl << endl;
  26.     else
  27.         cout << "Такого элемента нету." << endl << endl;
  28.  
  29.     input_sort(arr, N);
  30.     cout << "Отсортированный массив: " << endl;
  31.     print(arr, N);
  32.  
  33.     cout << "Введите искомый элемент: ";
  34.     cin >> k;
  35.     if (bin_srch(arr, N, k))
  36.         cout << "Элемент найден!" << endl << endl;
  37.     else
  38.         cout << "Такого элемента нету." << endl << endl;
  39.    
  40.     return 0;
  41. }
  42.  
  43. void input(int *arr, int n) {
  44.     for (int i = 0; i < n; i++) {
  45.         arr[i] = rand() % 101 - 50;
  46.     }
  47. }
  48.  
  49. void print(int *arr, int n) {
  50.     for (int i = 0; i < n; i++) {
  51.         cout << arr[i] << ' ';
  52.     }
  53.     cout << '\n';
  54. }
  55.  
  56. void input_sort(int *arr, int n) {
  57.     for (int i = 1; i < n; i++) {
  58.         int cur = i;
  59.         while (arr[cur - 1] > arr[cur] && cur > 0) {
  60.             swap(arr[cur - 1], arr[cur]);
  61.             cur--;
  62.         }
  63.     }
  64. }
  65.  
  66. bool bin_srch(int *arr, int n, int t) {
  67.     int l = 0, r = n - 1, m;
  68.     while (l < r) {
  69.         m = (l + r) / 2;
  70.         t > arr[m] ? l = m + 1 : r = m;
  71.     }
  72.     if (t == arr[l]) return true;
  73.     return false;
  74. }
  75.  
  76. bool line_srch(int *arr, int n, int t) {
  77.     for (int i = 0; i < n; i++) {
  78.         if (arr[i] == t) return true;
  79.     }
  80.     return false;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement