The implementation of the C language found by the dichotomy method:

Source: Internet
Author: User

#include <stdio.h>int binsearch (int, int, int); main () {int I, n = ten, x = 7; This assumes that the array a[] is defined as a[n], which is wrong and cannot be defined as a variable-length array. int a[10]; printf ("Please enter your num:/n"); The only way to assign a value to an array from a standard input: with a For loop for (i=0;i<n;i++) {scanf ("%d", &a[i]); } printf ("The%d can be found in the arr, it is%dth of the arr/n", X, Binsearch (X,a,n));} /* The first method, inferred all within the loop */int binsearch (int x, int a[], int n) {int low, high, mid; Low = 0; High = n-1; Note that this must be done with <=, with < incorrect, always returning-1 while (low <= high) {mid = (low + high)/2; if (x < A[mid]) high = mid-1; else if (x > A[mid]) low = mid + 1; else return mid; } return-1;} /* Run a test method within the loop *//*int binsearch (int x, int a[], int n) {int low, high, mid; Low = 0; High = n-1; Mid = (low + high)/2; while (low <= high) && (a[mid]!=x)) {if (x < a[mid]) = mid-1; else Low = mid + 1; Mid = (low + high)/2; } if (A[mid] = = x) return mid; else return-1;} */

Complexity of Time log2n

The implementation of the C language found by the dichotomy method:

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.