001    /*
002     * Created on 15.12.2004
003     *
004     * $Log:$
005     *
006     */
007    package de.hska.info1.uebung.suchen;
008    
009    /**
010     * BinaerSuche enthält eine iterative Imlementierung
011     * der binären Suche einer Zahl in einem aufsteigend
012     * sortiertem Feld.
013     * 
014     * @author Christian Pape
015     */
016    public class BinaerSuche {
017        
018        /**
019         * Sucht die gegeben Zahl z im Feld a mit
020         * binärere Suche (iterative Variante).
021         * Zeitaufwand O(log n).
022         */
023        boolean binaerSuchen(int [] a, int z) {
024          int links = 0;
025          int rechts = a.length-1;
026          while (links <= rechts) {
027            int mitte = (links+rechts)/2;
028            if (a[mitte] == z) {
029              return true; 
030            } else if ( z < a[mitte] ) {
031              rechts = mitte-1;
032            } else {
033              links = mitte+1;
034            }
035          }
036          return false;
037        }
038        
039    }