[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