Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.6 kB
1
Indexable
Never
#include <iostream>
#include <algorithm>


int getRandomNumber() {
    return rand() % 100; 
}

int binarySearch(int arr[], int low, int high, int key) {
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == key) {
            return mid;
        }
        else if (arr[mid] < key) {
            low = mid + 1;
        }
        else {
            high = mid - 1;
        }
    }
    return -1; 
}

int main() {
    setlocale(LC_ALL, "Russian");
    const int size = 30;
    int B[size];

    for (int i = 0; i < size; i++) {
        B[i] = getRandomNumber();
    }

    std::cout << "Массив B: ";
    for (int i = 0; i < size; i++) {
        std::cout << B[i] << " ";
    }
    std::cout << std::endl;

    
    int A[size];
    int uniqueElements = 0;
    std::sort(B, B + size);
    for (int i = 0; i < size; i++) {
        if (i == 0 || B[i] != B[i - 1]) {
            A[uniqueElements++] = B[i];
        }
    }

    std::cout << "Массив A: ";
    for (int i = 0; i < uniqueElements; i++) {
        std::cout << A[i] << " ";
    }
    std::cout << std::endl;

    int key;
    std::cout << "Введите элемент для бинарного поиска: ";
    std::cin >> key;

    int result = binarySearch(A, 0, uniqueElements - 1, key);
    if (result == -1) {
        std::cout << "Элемент не найден." << std::endl;
    }
    else {
        std::cout << "Элемент " << key << " найден в позиции " << result + 1 << " массива A." << std::endl;
    }

    return 0;
}
Leave a Comment