Searching: linear and binary · Busca: linear e binária
Two ways to search
- Searching means finding where a value is in an array (or saying it is not there).
- Linear search checks every item one by one. It works on any array.
- Binary search is much faster but needs the array to be sorted first.
Duas formas de buscar
- Buscar significa encontrar onde um valor está em uma matriz (ou dizer que não existe).
- Busca linear verifica cada item um por um. Funciona em qualquer matriz.
- Busca binária é muito mais rápida, mas precisa que a matriz esteja ordenada antes.
Linear search
- Walk from index
0ton - 1, comparing each item to the target. - Return the index the moment you find it. If you reach the end, return
-1. - For an array of
nitems, this looks at up tonof them.
Busca linear
- Percorra do índice
0atén - 1, comparando cada item com o alvo. - Retorne o índice no momento em que encontrar. Se chegar ao final, retorne
-1. - Para uma matriz de
nitens, isso verifica aténdeles.
Why sorting enables binary search
- If the array is sorted, you can jump to the middle and compare.
- If the middle is too small, the target must be in the right half; if too big, the left half.
- Each step throws away half the array, so it is very fast (about
log2(n)steps).
Por que ordenação habilita busca binária
- Se a matriz estiver ordenada, você pode pular para o meio e comparar.
- Se o meio for muito pequeno, o alvo deve estar na metade direita; se muito grande, na esquerda.
- Cada passo descarta metade da matriz, então é muito rápido (cerca de
log2(n)passos).
low, high, mid
- Keep two bounds:
low(start) andhigh(end). The middle ismid = low + (high - low) / 2. - If
a[mid]is the target, returnmid. Ifa[mid] < target, movelow = mid + 1; elsehigh = mid - 1. - Stop when
low > high— the target is not there, so return-1.
low, high, mid
- Mantenha dois limites:
low(início) ehigh(fim). O meio émid = low + (high - low) / 2. - Se
a[mid]for o alvo, retornemid. Se fora[mid] < target, movalow = mid + 1; caso contrário, movahigh = mid - 1. - Pare quando
low > high— o alvo não está lá, então retorne-1.
#include <stdio.h>
int main(void) {
int a[] = {1, 3, 5, 7, 9}; // sorted!
int target = 7, lo = 0, hi = 4, found = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) { found = mid; break; }
if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
printf("%d\n", found); // 3
return 0;
}
Common mistakes
- Binary search needs a sorted array.
- Linear search checks each element in turn.
Erros comuns
- A busca binária precisa de um array ordenado.
- Busca linear verifica cada elemento em sequência.
Now you try
- For binary search, assume the array is already sorted. Use
low,high, andmid. - Return
-1when the value is not found. Do not write amain— the checker provides one.
Agora você tenta
- Para busca binária, assuma que a matriz já está ordenada. Use
low,highemid. - Retorne
-1quando o valor não for encontrado. Não escreva ummain— o verificador fornece um.
Linear vs binary search · Busca linear vs busca binária
Binary search halves the range each step. · Busca binária divide o intervalo ao meio a cada passo.
Complete int linear_search(const int a[], int n, int target) so it returns the index of the first target, or -1 if it is not in the array. Do not · não write a main. · Complete int linear_search(const int a[], int n, int target) para que retorne o índice do primeiro target, ou -1 se não estiver no array. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int binary_search(const int a[], int n, int target) for a sorted array. Return the index of target, or -1. Use low, high, and mid. Do not · não write a main. · Complete int binary_search(const int a[], int n, int target) para um array ordenado. Retorne o índice de target, ou -1. Use low, high e mid. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int first_negative(const int a[], int n) so it returns the index of the first item less than 0, or -1 if there is none. Do not · não write a main. · Complete int first_negative(const int a[], int n) para que retorne o índice do primeiro item menor que 0, ou -1 se não houver nenhum. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.