There is such an array A , the size is N , 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 t in a position in the. Is there a better way to do it than to traverse it sequentially?
The solution to the problem is very interesting.
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 go 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.
void Printfarray (int a[], int n) { for (int i = 0; i < n; i++) printf ("%d", A[i]); Putchar (' \ n '); } 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; }
And this is similar to this topic:
There is an int array, and the difference between each of the two adjacent numbers is either 1 or-1. Now given a number, it is required to find the position of the number in the array.
The absolute value of the adjacent element difference is 1, and the target element is found in such an array.