01-complexity 3 binary search, 01-Binary Search

Source: Internet
Author: User

01-complexity 3 binary search, 01-Binary Search

This is a function question. The question provides corresponding interfaces to complete the subfunction. The given function interfaces and struct are defined as follows:

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 10
#define NotFound 0
Typedef int ElementType;

Typedef int Position;
Typedef struct LNode *List;
Struct LNode {
     ElementType Data[MAXSIZE];
     Position Last; /* Saves the position of the last element in the linear table */
};

List ReadInput(); /* Referee implementation, details are not listed. The element is stored starting from subscript 1 */
Position BinarySearch( List L, ElementType X );

Int main()
{
     List L;
     ElementType X;
     Position P;

     L = ReadInput();
     Scanf("%d", &X);
     P = BinarySearch( L, X );
     Printf("%d\n", P);

     Return 0;
}

/* Your code will be embedded here */

We can see that we need to perform binary search for a linear table stored in a linked list. The procedure is as follows:

Position BinarySearch( List L, ElementType X )
{
    Position mid;
    Position low = 1;
    Position high = L->Last;
    while(low <= high) {
        mid = low + (high - low)/2;
        if(X < L->Data[mid]) 
            high = mid - 1;
        else if (X > L->Data[mid]) 
            low = mid + 1;
        else 
            return mid;
    }
    return NotFound ;    
} 

Note that the while LOOP condition must be Left <= Right. Otherwise, when the two indicate the same number, "NotFound" is directly considered if the condition does not enter the loop judgment, resulting in incorrect results.


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.