Interview Questions: Find a node in the array

Source: Internet
Author: User
Question:

The original ordered array (assuming Ascending Order) is divided into two parts, and then the two parts are exchanged to get a new array. Write a function. The parameter is the new array. You need to find the node separated by the array and consider the time complexity.

Solution 1: traverse the array and find the number where the first one is greater than the last one. Otherwise, the last number is returned. Time complexity O (n ). Solution 2: Binary Search, time complexity O (lgn ). Note that you cannot use Mid + 1 in binary mode. Otherwise, you will miss the node.
# Include <iostream> using namespace STD; int find (int A [], int I, Int J) {if (I <0 | j <0) Return-1; if (I> = J) return I; int mid = (I + J)/2; If (mid = I) // J = I + 1 return I; if (A [Mid]> A [I]) return find (A, mid, J); // This cannot be replaced by mid + 1, otherwise, the node elsereturn find (A, I, mid-1);} int main () {int A [11] = {5, 6, 7, 8, 9, 10, 2, 3, 4}; // int A [11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int Len = sizeof (a)/sizeof (INT ); int Index = find (A, 0, len-1); If (index! =-1) cout <"the" <index <"th number:" <A [Index] <Endl ;}
Output:
The 5th number: 10

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.