First look at the topic requirements (Topic Source: Http://weibo.com/lirenchen, hereby acknowledge):
There is an array a, the size n, and the absolute value of the difference between the adjacent elements 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 iterate through it in turn?
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]). Because the absolute value of the difference between each adjacent number is 1. So the number before the T position must be smaller than Y. So direct positioning to array[t], recalculate t,t = ABS (Y–array[t]), and then repeat the above steps. This algorithm mainly utilizes the difference between the number of the current position and the lookup number to realize the leap-forward search. Algorithm efficiency is higher than the algorithm to traverse the array, and easy to implement. The complete code is as follows:
///"the series of the vernacular classic algorithm" "one step thousands of miles" array find//by Morewindows (http://blog.csdn.net/MoreWindows)//Welcome Attention Http://weibo.com/mor Ewindows #include <stdio.h> #include <math.h> 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_ind
Ex
Next_arrive_index + ABS (Find_number-arr[next_arrive_index]);
} return-1;
int main () {printf ("" "The First" "in the Vernacular classic algorithm series)" "One step thousands of miles" of the array find \ n ");
printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n");
printf ("--http://blog.csdn.net/morewindows/article/details/10645269--\ n \ nthe");
const int MAXN = 10;
int ARR[MAXN] = {4,5,6,5,6,7,8,9,10,9};
Printfarray (arr, MAXN); for (inti = 0; i < MAXN;
i++) printf ("Find%d \ t subscript%d\n", Arr[i], Findnumberinarray (arr, MAXN, arr[i));
printf ("Find%d \ t subscript%d\n",-1, Findnumberinarray (arr, MAXN,-1));
printf ("Find%d \ t subscript%d\n", 0, Findnumberinarray (arr, MAXN, 0));
printf ("Find%d \ t subscript%d\n", Findnumberinarray (arr, MAXN, 100));
return 0; }
The results of the operation are shown in the following illustration:
This article address: http://blog.csdn.net/morewindows/article/details/10645269