There is an array a, size n, and the absolute value of the adjacent element difference is 1.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.