There is an array a, size n, and the absolute value of the adjacent element difference is 1. such as: a={4,5,6,5,6,7,8,9,10,9}. Now, given the A and the target integer t, find the position of T in a. Is there a better way to do it than to traverse it sequentially?
Idea: The first number of arrays is array[0], the number to find is Y, set t = ABS (Y-array[0]). Since the absolute value of each adjacent number difference is 1. So the number before the T position is definitely smaller than Y. So navigate directly to Array[t], recalculate t,t = ABS (y–array[t), and repeat the above steps. This algorithm mainly uses the difference between the number of the current position and the number of lookups to realize the leap-through search. The efficiency of the algorithm is higher than the algorithm of traversing the array, and it is easy to implement.
int Findnumberinarray (int arr[], int n, int find_number) {int next_arrive_index = ABS (find_number-arr[0]); while (Next_arrive_index < n) {if (arr[next_arrive_index] = = Find_number) return next_arrive_index; Next_arrive_index + = ABS (Find_number-arr[next_arrive_index]); } return-1; }
Expansion: There is an int array, the difference between each two consecutive numbers is not 1 or 1. Now given a number, it is required to find the position of the number in the array.
This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1843587
There is an array a, size n, and the absolute value of the adjacent element difference is 1.