PHP implements algorithm analysis for finding the smallest absolute value in an ordered array and absolute value algorithm analysis
This example describes the PHP Algorithm for Finding the minimum absolute value of an ordered array. We will share this with you for your reference. The details are as follows:
Problem:
In an ordered array, the value may have a negative value or not. You need to find the value with the smallest absolute value.
Method 1:
Traverse the array to find the minimum absolute value, time complexity O (n), and n as the number of elements.
Method 2:
Binary Search, because the array is ordered, you can use binary search, time complexity O (logn ).
Analysis steps:
1. If the first number is a positive number, it indicates that the entire array does not have a negative number, and the first number is directly returned.
2. If the last number is negative, it indicates that the entire array does not have a positive number and the last number is directly returned.
3. the array element has positive and negative values, indicating that the element with the smallest absolute value must be at the junction of positive and negative numbers and must be searched for in two places:
①. If a [mid] <0, because the array is in ascending order, it means that the smallest number of absolute values will not appear on the left of a [mid], and the positive and negative values of the elements of a [mid + 1] are determined, if it is a negative number, you need to search in the range on the right of the mid. If a [mid-1] is not negative, it indicates that these two numbers are positive and negative vertices in the array, returns a smaller absolute value of the two numbers.
②. If a [mid]> 0, because the array is in ascending order, it means that the smallest number of absolute values will not appear on the right side of a [mid], and the positive and negative values of the elements of a [mid-1] are determined, if it is a negative number, it indicates that the two numbers are positive and negative vertices in the array. the return value is smaller than the absolute values of the two numbers. If a [mid-1] is not negative, you need to search in the left range of the mid.
3. If a [mid] = 0, a [mid] is an absolute smallest element.
Function selectAbsMinNum (array $ arr) {$ start = 0; $ len = count ($ arr)-1; if ($ arr [0]> 0) {// return $ arr [0];} if ($ arr [$ len] <0) {// return $ arr [$ len];} while ($ start <$ len) {$ mid = floor ($ start + $ len)/2); if ($ arr [$ mid]> 0) {if ($ arr [$ mid-1]> 0) {$ len = $ mid-1;} else {return min ($ arr [$ mid], -$ arr [$ mid-1]) ;}} elseif ($ arr [$ mid] <0) {if ($ arr [$ mid + 1] <0) {$ start = $ mid + 1;} else {return min (-$ arr [$ mid], $ arr [$ mid + 1]);} else {return $ arr [$ mid] ;}}$ sortArr = [-5,-4,-4,-4, 5, 7, 9]; echo selectAbsMinNum ($ sortArr), PHP_EOL;
Running result: 4