Sie sind auf Seite 1von 3

Binary Search C Code Page 1 of 3

Monday, July 12, 2010

Search
Search Ke

Ads by Google Algorithm C Programming Programming Examples Programming C++ B

» C Algorithms » Binary Search


C Programming Lang

Home
Binary Search C Programming L
C Data Structures
Great SQL Tutorial
Simple Tips for SQL Programming Blog by Rick F. van C Algorithms
der Lans C Code Snippets
cs.pervasive.com/blogs/sql4psql
C Sitemap

Parallel Port Programming In C C Programming R


The latest & greatest in parallel computing. Visit our
expert blog!
www.drdobbs.com/Go-Parallel

Flowcharts from C/C++


CallFlow, DataFlow, Code Metrics Trees, Static Check,
Documentation
www.sgvsarc.com

Binary search is an algorithm for finding the location of an element in a sorted list. First, it
checks the middle element of the sort list; if that element is equal to the sought value then
the location has been found; Othewise, the lower half or upper half is chosen for next
searching based on the sought value less than or greater than the middle element. By
doing so, this binary search reduces the number of elements to be checked by a factor of
two each time searching and find the element in logarithmic time.

Helpful Programming

PHP Tutorial website


PHP tutorial to help y
skill quickly.

If you want to learn P


check it out the Perl T

http://cprogramminglanguage.net/binary-search-c-code.aspx 7/12/2010
Binary Search C Code Page 2 of 3

Binary Search Flowchart

Binary Search implemented in C.

01. int binary_search(int sorted_list[], int low, int high, int


element) {
02. while (low <= high) {
03. int middle = low + (high ‐ low)/2;
04. if (element > sorted_list[middle])
05. low = middle + 1;
06. else if (element < sorted_list[middle])
07. high = middle ‐ 1;
08. else
09. return middle;
10. }
11. return ‐1;
12. }

http://cprogramminglanguage.net/binary-search-c-code.aspx 7/12/2010
Binary Search C Code Page 3 of 3

Binary Search in using recursion technique.

01. int binary_search(int sorted_list[], int low, int high, int


element) {
02. if (high < low)
03. return ‐1;
04. int middle = low + (high ‐ low)/2;
05. if (element < sorted_list[middle])
06. return binary_search(sorted_list, low, middle‐1,
element);
07. else if (element > sorted_list[middle])
08. return binary_search(sorted_list, middle+1, high,
element);
09. else
10. return middle;
11. }

Flowcharts from C/C++


CallFlow, DataFlow, Code Metrics Trees, Static Check,
Documentation
www.sgvsarc.com

Windows 7 Programming
Programming tips from MS insiders. Ribbon. Task bar.
Annimation. Go!
ddj.com

HPC Solutions from Dell™


Leverage Technological Advances w/ Integrated HPC
Soln from Dell™
www.Dell.Com/HPC

Delicious Digg reddit Facebook StumbleUpon

« Previous page Next page »

Copyright by CProgrammingLanguage.net 2007 - 2010, your guide to C Programming Language. Privacy

http://cprogramminglanguage.net/binary-search-c-code.aspx 7/12/2010

Das könnte Ihnen auch gefallen