There is an array of already sorted (ascending), there may be positive, negative, or 0 in the array, and the minimum number of elements in the array is required, and the method that cannot be used in sequential comparison (complexity requires less than O (n)) can be implemented in any language such as array { -20,-13,-4, 6, 77,200}, The smallest absolute value is-4.
Problem decomposition:
Step one: Binary search for changing the position of the symbol (0 as a positive number)
Step two: Compare the absolute size of the left and right digits, and take the smaller one
<script language= "JavaScript" > var getbound = function (a,fr,to) {//[fr,to] is the candidate location interval, where the position begins with 0 Count V
AR b=fr,f=fr,t=to,s=true; var left=function (b) {return a[b-1];};/ /Get the number to the right of the location, add code readability var right=function (b) {return a[b];};/ /Get the number on the left of the location, add code readability if (a.length===0) {return-1;//array is empty, return-1}else{if (right) >=0) {s=false;//Initialization location is the location to find}else{for (var i=1;i<=100 && s;i + +) {B=f+math.ceil ((t-f)/2);//Find Midpoint if (right (b) ===undefined| | (Left (b) <0 && right (b) >=0)) {s=false;//midpoint is the location to find}else if (right (b) <0) {f=b;
Next time, find the midpoint}else{t=b;//the next step back and find the midpoint}}
return b;
}
}; var getminabs = function (a) {var b=getbound (A,0,a.length)//Get position if (b>=0) {if (b===0) {return Math.Abs (a[b));//Position on leftmost }else if (b===a.length) {return Math.Abs (a[b-1));/position on rightmost}else{R Eturn (Math.Abs (a[b)) >math.abs (A[b-1])?
Math.Abs (A[b-1]): Math.Abs (A[b]);//position in middle}}else{return false;
}
};
Test code var myarray=[-20,-13,-4,0,0,0,6,77,200,201,202];
Alert ("[" + MyArray + "]:" + getminabs (myarray));
var myarray=[];
Alert ("[" + MyArray + "]:" + getminabs (myarray));
var myarray=[-1];
Alert ("[" + MyArray + "]:" + getminabs (myarray));
var myarray=[1];
Alert ("[" + MyArray + "]:" + getminabs (myarray));
var myarray=[0,0];
Alert ("[" + MyArray + "]:" + getminabs (myarray));
var myarray=[-1,-1];
Alert ("[" + MyArray + "]:" + getminabs (myarray)); </script>
Take myarray=[-20,-13,-4,0,0,0,6,77,200,201,202] For example, the test pops up: