Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,219 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,227 people online right now. Registration is fast and FREE... Join Now!





Recursive Binary Searching

Traverses a sorted list to find data

Submitted By: KYA
Actions:
Rating:
Views: 192

Language: C++

Last Modified: July 18, 2008
Instructions: Use this to find items within an array once it has already been sorted. The returned ints can be used in a variety of ways.

Snippet


  1. int BinarySearch(int A[], int value, int low, int high)
  2. {
  3.     if (high < low)
  4.     {
  5.         return -1; // not found
  6.     }
  7.     int mid = (low + high) / 2;
  8.     if (A[mid] > value)
  9.     {
  10.        return BinarySearch(A, value, low, mid-1);
  11.     }
  12.     else if (A[mid] < value)
  13.     {
  14.        return BinarySearch(A, value, mid+1, high);
  15.     }
  16.     else
  17.     {
  18.       return 1; // found
  19.     }
  20. }//end Binary Search
  21.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month