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