2015 where to go programming question 1

Source: Internet
Author: User

[Programming questions] two-point search

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.

Test examples:
[1,3,5,7,9],5,3
Returns: 1

The code is as follows:
Import java.util.*;p Ublic class BinarySearch {public    int getPos (int[] A, int n, int val) {        //write code here
   
    return BinarySearch (a,0,n-1,val);    }        int BinarySearch (int[] a,int begin,int end,int val) {        int mid=begin+ (end-begin)/2;        while (begin<=end) {            if (Val==a[mid]) {                int ret=mid;                while (ret-1>=0) {                    if (a[ret-1]==val)                        ret--;                    else break;                }                return ret;            }            else if (Val<a[mid]) {               return BinarySearch (A,begin,mid-1, Val);            } else{                begin=mid+1;               Return  BinarySearch (A,mid+1,end, Val);                            }        }         return-1;}    }
   

  

2015 where to go programming question 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.