Ordered array Ordering

Source: Internet
Author: User

Problem:

Given an array, the value is incremented from small to large, and the maximum value is found by descending from the largest to the smallest.

Idea: The simplest way is to start with the second value and decide whether to meet A[i] > A[i-1] && a[i] > a[i+1]. If satisfied, I is the subscript for that maximum value. The complexity of the algorithm is O (n).

We can improve this algorithm, because this array is ordered, so we can use the idea of binary lookup, more quickly find the maximum value, time complexity of O (LG N).

Binary search algorithm can be found at the back of link, the exit condition of the binary search and the exit condition of the problem is not the same (see while loop), this is a very noteworthy place.

http://blog.csdn.net/beiyeqingteng/article/details/5736004

[Java]View PlainCopy
  1. public int Turningpoint (int[] A) {
  2. int m = a.length;
  3. int begin = 0;
  4. int end = M- 1;
  5. int TP = begin + (end-begin)/2;
  6. //The condition "TP > 0 && TP < m-1" makes sure that TP isn't at the beginning or the end
  7. While (TP > 0 && TP < m-1) {
  8. if (A[TP] > A[TP + 1] && A[TP] > A[TP-1]) {
  9. return TP;
  10. } Else if (A[TP] < a[tp+1]) {
  11. BEGIN = TP + 1;
  12. TP = begin + (end-begin)/2;
  13. } Else {
  14. END = TP- 1;
  15. TP = begin + (end-begin)/2;
  16. }
  17. }
  18. return-1;
  19. }

Ordered array Ordering

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.