Selasa, 23 Juli 2013

Membuat struktur data dengan binary search


Berikut source code nya:





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

/**
 *
 * @author MACHAAPIEDH
 */
public class binarySearch {
     public static void main (String [] args){
      int bil []= new int [5];
      bil[0]=20;
      bil[1]=35;
      bil[2]=40;
      bil[3]=60;
      bil[4]=90;
     
      int low, mid, high;
      low = 0;
      high = bil.length-1;
     
      for (int i=0; i<bil.length; i++){
          System.out.print(bil[i]+" ");
      }
      System.out.println("");
     
      int key = 35;
      boolean belumKetemu = true;


     while (belumKetemu){
          mid = (low+high)/2;
          if (bil [mid] == key){
            belumKetemu = false;
              System.out.println("bilangan Ditemukan " +key);
             
          }
          else if(low > high) {

System.out.println(" tidak ditemukan " + key);
     break;
          }
         
          else {
              if (bil [mid]<key){
              low = high + 1;
          }
          else {
              high = mid - 1;
          }
      }
         
      }
    }
}

Penampakan: 


Tidak ada komentar:

Posting Komentar

Entri Populer