Skip to content

Instantly share code, notes, and snippets.

@PawelKac
Created January 7, 2021 11:03
Show Gist options
  • Save PawelKac/867cbd68239199984958dd7217cc6b55 to your computer and use it in GitHub Desktop.
Save PawelKac/867cbd68239199984958dd7217cc6b55 to your computer and use it in GitHub Desktop.
binary search algorithm/algorytm wyszukiwania binarnego
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
int[] tab = {-3, -1, 0, 2, 8, 12, 15, 20, 27, 29, 45}; //lista musi być posortowana
Scanner input = new Scanner(System.in);
System.out.print("Wprowadź liczbę: ");
int findElement = input.nextInt();
int score = find(tab, findElement);
if (score == Integer.MAX_VALUE){
System.out.print("Tablica nie zawiera wprowadzonej liczby");
} else {
System.out.println("Liczba jest w tabeli");
}
}
public static int find(int[] tab, int findElement){
int index = Integer.MAX_VALUE;
int min = tab[0];
int max = tab.length - 1;
while (min <= max){
int half = (min + max) / 2; //zmniejszamy przedział szukanych liczb o połowę
if(tab[half] < findElement){
min = half + 1;
} else if (tab[half] > findElement) {
max = half - 1;
} else if (tab[half] == findElement){
index = half;
break;
}
}
return index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment