Subject:
There is an sorted array (ascending). The array may have positive numbers, negative numbers, or 0. It is required to obtain the minimum absolute value of the elements in the array, the sequential comparison method is not supported (the complexity must be less than O (N) and can be implemented in any language.
For example, for an array {-20,-13,-4, 6, 77,200}, the minimum absolute value is-4.
How can I find this question?
The initial solution is as follows:
1. All elements in the array are positive, and the leftmost number is used;
2. All elements in the array are negative, and the absolute value of the rightmost number is obtained;
3. If there is a positive number and a negative number in the array, you can use the binary lookup Method to Determine the symbols of the intermediate element.
A) if the intermediate element is positive, continue to judge the symbol of the element before the intermediate element.
B) if the intermediate element is negative, judge the symbol of the next element of the intermediate element.
C) The intermediate element is zero, so that it is equal to the returned result value.
Below is the code implementation based on the above ideas, there should be Vulnerabilities
# Include "stdafx. H "# include <iostream> using namespace STD; // obtain the int minabsolute (INT arr [], int size), which is the smallest absolute value in the array ); // return the smaller values of two numbers: int compare (int A, int B); int _ tmain (INT argc, _ tchar * argv []) {int A [10] = {-10,-8,-5,-3, 2, 5, 8, 9, 11, 15}; int size = sizeof (a)/sizeof (INT ); int result = minabsolute (A, size); cout <"the smallest number of absolute values is:" <result <Endl; return 0;} int minabsolute (INT arr [], int size) {int first, last, mid; first = 0; last = size-1; int result; // The number in the array is all negative, take the rightmost number if (ARR [0] <0 & arr [size-1] <0) {result = arr [size-1];} // The number in the array is all positive. Take the leftmost number else if (ARR [0]> 0 & arr [size-1]> 0) {result = arr [0];} // The array has positive and negative values. The binary search else {While (first <last) {int mid = (first + last)/2; if (ARR [Mid]> 0) {If (ARR [Mid-1]> 0) {last = mid-1 ;} else if (ARR [Mid-1] <0) {result = compare (-Arr [Mid-1], arr [Mid]); break ;} else {result = arr [Mid-1]; break ;}} else if (ARR [Mid] <0) {If (ARR [Mid + 1] <0) {First = Mid + 1;} else if (ARR [Mid + 1]> 0) {result = compare (-Arr [Mid], arr [Mid + 1]); break;} else {result = arr [Mid + 1]; break;} else {result = arr [Mid]; break ;}} return result ;} int compare (int A, int B) {If (A> B) {return B ;}else {return ;}}