Selasa, 05 Juni 2012

Java Binary Search Algorithm

/* Snippet: Binary Search
 * Author: SPlutard
 *
 *Description: An efficient method for searching SORTED arrays. Returns the number if found, otherwise returns -1.
 */

public static int binarySearch(int[] list, int listLength, int searchItem) {
    int first=0;
    int last = listLength - 1;
    int mid;
   
    boolean found = false;
   
    //Loop until found or end of list.
    while(first <= last &&!found) {
        //Find the middle.
        mid = (first + last) /2;
       
        //Compare the middle item to the search item.
        if(list[mid] == searchItem) found = true;
        else { //Not found, readjust search parameters, halving the size & start over.
            if(list[mid] > searchItem) last = mid -1;
            else first = mid + 1;
        }
    }
   
    if(found) return mid;
    else return(-1);
}

0 komentar:

Posting Komentar

resep donat empuk ala dunkin donut resep kue cubit coklat enak dan sederhana resep donat kentang empuk lembut dan enak resep es krim goreng coklat kriuk mudah dan sederhana resep es krim coklat lembut resep bolu karamel panggang sarang semut

Copyright © Deja Area | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com | BTheme.net      Up ↑