Binary Search Step By Step di Java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package binary;
import java.util.Scanner;
/**
*
* @author ANGGA
*/
public class binary {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner data=new Scanner(System.in);
int[] angka={1,2,3,4,5,6,7,8,9};

for(int i=0;i<angka.length;i++){
System.out.print(angka[i]+” “);
}
System.out.println();

boolean ketemu=false;
System.out.print(“Masukkan angka yang dicari : “);
int cari=data.nextInt();

int awal=0;
int akhir=angka.length-1;
int tengah=0;

while(awal<=akhir && !ketemu){
tengah=(awal+akhir)/2;

System.out.println(“Awal : “+awal);
System.out.println(“tengah : “+tengah);
System.out.println(“Akhir : “+akhir);
System.out.println();

if(angka[tengah]==cari){
ketemu=true;
}
if(cari<angka[tengah]){
akhir=tengah-1;
}
if(cari>angka[tengah]){
awal=tengah+1;
}

}

if(ketemu=true){
System.out.println(“Angka “+cari+” Ketemu di Index “+tengah);
}
else{
System.out.println(“Angka “+cari+” TIDAK Ketemu”);

}

}

}

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout /  Ubah )

Foto Google

You are commenting using your Google account. Logout /  Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout /  Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout /  Ubah )

Connecting to %s