Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Algoritmos de Busca Binária #135

Closed
vinicius-developer opened this issue Apr 17, 2022 · 1 comment
Closed

Algoritmos de Busca Binária #135

vinicius-developer opened this issue Apr 17, 2022 · 1 comment
Assignees

Comments

@vinicius-developer
Copy link
Contributor

Enquanto estava implementando o algoritmo de busca binária em java, executei um teste para procurar um item maior do que o maior item de lista, foi quando eu me deparei com uma Exception.

Ela acontecia porque eu estava passando o maior índice da lista com o atributo length que retorna o total de elementos, o problema é que como os índices de array começam em 0 quando ele ia comparar o último índice ele tentava sempre procurar o número errado já que a atributo length começa em 1.

Acredito que o mesmo erro possa acontecer em outros algoritmos, Por exemplo, consegui executar o teste em python e junto com essa issue vou subir um pr com a alteração para remover o bug.

@ricardocarva
Copy link
Collaborator

Hi @vinicius-developer. I am not sure if you have fixed this issue as or not as this PR has been opened for quite a while.

I ran the following code in a Java Playground, and I didn't experience any exceptions.

`public class BuscaBinaria
{
public int posicao;

BuscaBinaria(int[] array, int objetivo) {
this.posicao = BinarySearch(objetivo, array);
}

public int GetResultado() {
return this.posicao;
}

public int BinarySearch(int objetivo, int[] array) {
int comeco = 0;
int fim = array.length - 1;

while (comeco <= fim) {
  int meio = comeco + (fim - comeco) / 2;
  if (array[meio] == objetivo) return meio;
  if (array[meio] < objetivo) comeco = meio + 1;
  else fim = meio - 1;
}
return -1;

}

public static void main(String[] args) {
int[] array = {1, 3, 5, 7, 9, 11};
int objetivo = 15;
BuscaBinaria busca = new BuscaBinaria(array, objetivo);

int resultado = busca.GetResultado();
System.out.println("O índice do elemento " + objetivo + " é: " + resultado);

}
}
`

I did find a PR (#136) from you fixing this bug in the python algorithm.

As there was no further information on how to reproduce this issue and the PR is about 2 years old, I am closing this PR.

Should the issue be still present, please raise a new issue with more details.

Thank you!

@ricardocarva ricardocarva closed this as not planned Won't fix, can't repro, duplicate, stale Mar 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants