Binary search using the C language pointer and Recursive Method

Source: Internet
Author: User

Use the C language pointer and recursive method to achieve binary search, and use the input statement and print statement.

# Include
 
  
// Binary search init int binsearch (int low, int height, int * ptr, int); int main () {int I = 0; int arr [10]; int * ptr = arr; for (I = 0; I <10; I ++) scanf ("% d", arr + I); printf ("the input data is: \ n "); for (I = 0; I <10; I ++) printf (" % d ", arr [I]); printf ("\ n start half lookup \ n"); printf ("\ n input number to be searched \ n"); int m; scanf ("% d ", & m); int j; j = binsearch (0, 9, ptr, m); printf ("\ n * ptr = % d, j = % d \ n", * ptr, j); return 0;} int binsearch (int low, int height, int * ptr, int value) {if (ptr = NULL | low> height) return-1; printf ("\ nlow = % d, height = % d, \ n", low, height); if (* (ptr + low) = value) {ptr + = low; return low;} if (* (ptr + height) = value) {ptr + = height; return height;} if (low = height) {printf ("low = height = % d", low); if (* (ptr + low) = value) {ptr + = low; return low ;} else return-1;} int mid = (low + height)/2; int result; printf ("\ nlow = % d, height = % d, mid = % d \ n ", low, height, mid); printf (" * (ptr + mid) = % d, value = % d ", * (ptr + mid), value); // You must prevent the infinite loop if (* (ptr + mid) = value) caused by recursion when the queried value does not exist) {printf ("return mid = % d", mid); ptr + = mid; return mid;} else if (* (ptr + mid)> value) {return binsearch (low, mid-1, ptr, value);} else {return binsearch (mid + 1, height, ptr, value);} return-1 ;}
 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.