Skip to content

Instantly share code, notes, and snippets.

@YeyoM
Created February 21, 2023 18:37
Show Gist options
  • Save YeyoM/83e6052089290bb8a8878936e7f8b1a8 to your computer and use it in GitHub Desktop.
Save YeyoM/83e6052089290bb8a8878936e7f8b1a8 to your computer and use it in GitHub Desktop.
Binary Search in cpp
// Diego Emilio Moreno Sánchez
#include <iostream>
#include <stdlib.h>
using namespace std;
bool busquedaBinaria(int arr[], int tam, int valor) {
int inicio = 0;
int fin = tam - 1;
int medio;
while (inicio <= fin) {
medio = (inicio + fin) / 2;
if (arr[medio] == valor) {
return true;
} else if (arr[medio] < valor) {
inicio = medio + 1;
} else {
fin = medio - 1;
}
}
return false;
}
//Busqueda binaria
int main() {
int arr[] = {5, 2, 4, 6, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
bool encontrado = busquedaBinaria(arr, n, 5);
cout << encontrado << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment