“Búsqueda binaria” Código de respuesta

búsqueda binaria

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

Búsqueda binaria


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

Búsqueda binaria

class BinarySearchExample{  
 public static void binarySearch(int arr[], int first, int last, int key){  
   int mid = (first + last)/2;  
   while( first <= last ){  
      if ( arr[mid] < key ){  
        first = mid + 1;     
      }else if ( arr[mid] == key ){  
        System.out.println("Element is found at index: " + mid);  
        break;  
      }else{  
         last = mid - 1;  
      }  
      mid = (first + last)/2;  
   }  
   if ( first > last ){  
      System.out.println("Element is not found!");  
   }  
 }  
 public static void main(String args[]){  
        int arr[] = {10,20,30,40,50};  
        int key = 50;  
        int last=arr.length-1;  
        binarySearch(arr,0,last,key);     
 }  
} 
Ill Ibis

búsqueda binaria

class Solution {
  public:
  int search(vector<int>& nums, int target) {
    int pivot, left = 0, right = nums.size() - 1;
    while (left <= right) {
      pivot = left + (right - left) / 2;
      if (nums[pivot] == target) return pivot;
      if (target < nums[pivot]) right = pivot - 1;
      else left = pivot + 1;
    }
    return -1;
  }
};
Ayush Varma

Búsqueda binaria

// Java implementation of iterative Binary Search
class BinarySearch {
    // Returns index of x if it is present in arr[],
    // else return -1
    int binarySearch(int arr[], int x)
    {
        int l = 0, r = arr.length - 1;
        while (l <= r) {
            int m = l + (r - l) / 2;
 
            // Check if x is present at mid
            if (arr[m] == x)
                return m;
 
            // If x greater, ignore left half
            if (arr[m] < x)
                l = m + 1;
 
            // If x is smaller, ignore right half
            else
                r = m - 1;
        }
 
        // if we reach here, then element was
        // not present
        return -1;
    }
 
    // Driver method to test above
    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();
        int arr[] = { 2, 3, 4, 10, 40 };
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearch(arr, x);
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at "
                               + "index " + result);
    }
}
Sushant Mishra

Búsqueda binaria

10 101 61 126 217 2876 6127 39162 98126 712687 1000000000100 6127 1 61 200 -10000 1 217 10000 1000000000
Geek Amir

búsqueda binaria

function binarySearchRicorsivo(array A, int p, int r, int v)
    if p > r
      return -1
     if v < A[p] or v > A[r]
       return -1
     q= (p+r)/2
     if A[q] == v
       return q
     else if A[q] > v
       return binarySearchRicorsivo(A,p,q-1,v)
     else
     
CEO of knowledge

búsqueda binaria

binarySearch(arr, x, low, high)
           if low > high
               return False 
   
           else
               mid = (low + high) / 2 
                   if x == arr[mid]
                   return mid
       
               else if x > arr[mid]        // x is on the right side
                   return binarySearch(arr, x, mid + 1, high)
               
               else                        // x is on the right side
                   return binarySearch(arr, x, low, mid - 1)
Shubham Rathore

búsqueda binaria

# A recursive binary search function. It returns location of x in
# given array arr[l..r] is present, otherwise -1
def binarySearch(arr, l, r, x):
   if (r >= l):
        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;
  
# This code is contributed by umadevi9616
Faisal Ahmad

Búsqueda binaria

// C++ program to implement iterative Binary Search
#include <bits/stdc++.h>
using namespace std;
 
// A iterative binary search function. It returns
// location of x in given array arr[l..r] if present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
    while (l <= r) {
        int m = l + (r - l) / 2;
 
        // Check if x is present at mid
        if (arr[m] == x)
            return m;
 
        // If x greater, ignore left half
        if (arr[m] < x)
            l = m + 1;
 
        // If x is smaller, ignore right half
        else
            r = m - 1;
    }
 
    // if we reach here, then element was
    // not present
    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;
}
Siddhant

Respuestas similares a “Búsqueda binaria”

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código