“Бинарный алгоритм поиска” Ответ

Бинарный поиск

If you are setting mid = (left + right)/2, you have to be very careful.
Unless you are using a language that does not overflow such as Python,
left + right could overflow. 
One way to fix this is to use left+ (right−left)/2 instead.

If you fall into this subtle overflow bug, you are not alone.Even Jon Bentley's
own implementation of binary search had this overflow bug and remained 
undetected for over twenty years.
Ayush Varma

Бинарный алгоритм поиска

/*
Java Implementation of Binary Search Algorithm.
- Assuming the Array is Sorted (Ascending Order)
- returns the Index, if Element found.
- -1, if not found.
*/
public class BinarySearch {

    int binarysearch(int[] array, int element) {
        int a_pointer = 0;
        int b_pointer = array.length -1;
      	if (array[a_pointer] == element) return a_pointer;
        if (array[b_pointer] == element) return b_pointer;

        while(a_pointer <= b_pointer){
            int midpoint = a_pointer + (b_pointer - a_pointer) / 2;
          	if (array[midpoint] == element) return midpoint;
          
          	// ignoring the left half, if this is True.
            if (array[midpoint] < element) a_pointer = midpoint + 1;
          
          	// ignoring the right half, if this is True.
            else if (array[midpoint] > element) b_pointer = midpoint - 1;
        }
        return -1;	// Element not Found
    }
    public static void main(String[] args) {
        int[] list = {1, 2, 3, 4, 7, 9, 11, 12, 15, 19, 23, 36, 54, 87};
        System.out.println(binarysearch(list, 19));
    }
}
Prabhu Kiran Konda

Реализуйте бинарный поиск отсортированного массива целых чисел с использованием псевдокода.

# Here's the pseudocode for binary search, modified for searching in an array. The inputs are the array, which we call array; the number n of elements in array; and target, the number being searched for. The output is the index in array of target:

    1.Let min = 0 and max = n-1.
    2. Compute guess as the average of max and min, rounded down (so that it is an integer).
    3. If array[guess] equals target, then stop. You found it! Return guess.
    4. If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
    5. Otherwise, the guess was too high. Set max = guess - 1.
    6. Go back to step 2.
Handsome Hamster

Бинарный поиск

// C++ program to implement recursive Binary Search
#include <bits/stdc++.h>
using namespace std;
 
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    if (r >= l) {
        int mid = l + (r - l) / 2;
 
        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;
 
        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
 
        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid + 1, r, x);
    }
 
    // We reach here when element is not
    // present in array
    return -1;
}
 
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, 0, n - 1, x);
    (result == -1)
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result;
    return 0;
}
Mohsine El hadaoui

Бинарный поиск


const numbers = [1, 2, 3,4,5,6,7,8,9,10];

function binarySearch(sortedArray, key){
    let start = 0;
    let end = sortedArray.length - 1;

    while (start <= end) {
        let middle = Math.floor((start + end) / 2);
        console.log(middle)
        if (sortedArray[middle] === key) {
            // found the key
            return middle;
        } else if (sortedArray[middle] < key) {
            // continue searching to the right
            start = middle + 1;
        } else {
            // search searching to the left
            
            end = middle - 1;
        }
    }
	// key wasn't found
    return -1;
}

console.log(binarySearch(numbers,4))
Ill Ibis

Бинарный алгоритм поиска

#include <bits/stdc++.h>

using namespace std;

int binarySearch(int arr[], int l, int h, int key){
    if(l<=h){
        int mid = l + (h-l)/2;

        if(arr[mid] == key){
            return mid;
        }

        else if(arr[mid] > key){
            return binarySearch(arr, l, mid-1, key);
        }

        else if(arr[mid] < key){
            return binarySearch(arr,mid+1, h, key);
        }
    }       

    return -1;
}

int main(){
    int arr[] = {1,2,3,4,5,6,7,8,9,10};
    int n = sizeof(arr)/sizeof(arr[0]);
    int key = 7;

    int result = binarySearch(arr,0,n-1,key);

    (result==-1)
        ? cout << "Element is not found in the array" << endl
        : cout << "Element is found at index " << result;

    return 0;

}
Glamorous Gibbon

Ответы похожие на “Бинарный алгоритм поиска”

Смотреть популярные ответы по языку

Смотреть другие языки программирования