Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Упражнение 1: Задачa 1
- #include <iostream>
- #include <vector>
- #define SIZE 200
- using namespace std;
- int binarySearch( int searchElement, int data[], int length)
- {
- int low = 0;
- int high = length - 1;
- int middle = ( low + high + 1 ) / 2;
- int location = -1;
- do {
- if ( searchElement == data[ middle ] ){
- location = middle;
- }
- else if ( searchElement < data[ middle ] ) {
- high = middle - 1;
- }
- else {
- low = middle + 1;
- }
- middle = ( low + high + 1 ) / 2;
- } while ( ( low <= high ) && ( location == -1 ) );
- return location;
- }
- int main() {
- int nums[SIZE];
- int n;
- do
- {
- cout << "Enter number of elements: ";
- cin >> n;
- }
- while (n <= 0 || n > SIZE);
- for (int i = 0; i < n; i++)
- {
- cin >> nums[i];
- }
- int m;
- cout << "Enter element for search: ";
- cin >> m;
- if(binarySearch(m, nums, n) == -1){
- cout << "Not found!" << endl;
- } else {
- cout << m << " is found" << endl;
- vector<int> indexes; // dynamic array (vector)
- for (int i = 0; i < n; i++) {
- if (nums[i] == m){
- indexes.push_back(i);
- }
- }
- cout << "Indexes: ";
- for (vector<int>::iterator it = indexes.begin() ; it != indexes.end(); ++it){
- cout << *it << ", ";
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement