class BinSuche
{ static int[] feld;
  static final int maxIndex=9999;

  static void feldFuellen()
  { for (int i=0; i<=maxIndex; i++)
         feld[i] = (int)Math.round(Math.random()*9000.0 + 1000);
  } // feldFuellen

  static void feldAusgabe()
  { Out.println("Das Feld enthaelt die folgenden Elemente: ");
    for (int i=0; i<=maxIndex; i++) Out.print(feld[i] + " ");
    Out.println();
  } // feldAusgabe

  static void vertausche (int a, int b)
  {  int ablage = feld[a];
     feld[a] = feld[b];
     feld[b] = ablage;
  } // vertausche

  static void minsort()
  { int minpos;
    for (int i=0; i<=maxIndex; i++)
    { minpos = i;
      for (int k=i+1; k<=maxIndex; k++)
      {  if (feld[k]<feld[minpos]) { minpos = k; }
      } // for k
      if (minpos>i) { vertausche(i, minpos); }
    } // for i
  }  // minsort

  static int binaereSuche(int zahl)
  {  int low = 0;
     int mitte;
     int high = maxIndex;
     while (low <= high)
     {  mitte = (low + high) / 2;
        if (feld[mitte]==zahl) { return mitte; }
        else {  if (feld[mitte] < zahl) { low = mitte + 1; }
                else { high = mitte - 1; }
             }
     } // end while
     return -1; // nicht gefunden
  }

  public static void main(String[] arg)
  { feld = new int[maxIndex+1];
    int suchzahl = 1234;
    Out.println("Binaere Suche: ");
    feldFuellen();
    Out.println("Erst mal sortieren: ");
    minsort();
    Out.println("Beginn der Suche:");
    int pos = binaereSuche(suchzahl);
    if (pos>=0)
         { Out.println("Zahl " + suchzahl + " steht an Stelle " + pos );
           Out.println("Zur Kontrolle: feld[" + pos + "] = " + feld[pos]);
         }
    else Out.println(suchzahl + " wurde nicht gefunden.");
  } // main
} // class BinSuche
