Two-point Search

Source: Internet
Author: User

Title Description

For an ordered array, we usually use a binary lookup to locate an element, write a binary lookup algorithm, and find the specified element in the array.

Given an integer array A and its size n, given the element to find Val, return its position in the array (starting at 0), or 1 if the element does not exist. If the element appears more than once, return to the first occurrence of the position.

Enter a description

The first line enters N, which represents the length of the array

Enter n number in the second line

The third line enters the key value to find

Output description

Outputs an integer that represents the subscript of the array position where key is located, starting with 0

Input sample

5 1 3 5 7 9 5

Output sample

2

Test code

#include <stdio.h>#include<stdlib.h>intGetPos (int*a,intNintkey) {    intLow , high, mid; Low=0, high = n-1;  while(High >=Low ) {Mid= (low + high)/2; if(Key >A[mid]) { Low= Mid +1; }        Else if(Key <A[mid]) { High= Mid-1; }        Else        {             while(A[mid] = = A[mid-1]) {Mid--; }            returnmid; }    }    return-1;}intMain () {intN, Key; scanf ("%d", &N); int*a = (int*)calloc(N,sizeof(int));  for(inti =0; I < n; i++) {scanf ("%d", &A[i]); } scanf ("%d", &key); printf ("%d\n", GetPos (A, n, key));  Free(a); return 0;}





Two-point Search

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.