Returns the subscript of a specified key in a circular ordered array.

Source: Internet
Author: User

RT

A circular ordered array refers to the following Array

10 11 12 13 14 1 2 3 4 5 6 7 8 9

For ease of use, array elements are not the same.

Solution:

We can first divide it into two parts to determine whether the order on the left is correct.

If the order is on the left, determine whether the key is on the left.

If the left side is not ordered, it also determines whether the key is on the left.

If none of the above statements are true

The key may be on the right.

/*************************************** **************************************** # Author: neo Fung # Email: neosfung@gmail.com # Last modified: # filename: binsearch. CPP # description: **************************************** **************************************/# ifdef _ msc_ver # define debug # DEFINE _ crt_secure_no_deprecate # endif # include <fstream> # include <stdio. h> # include <Iost Ream> # include <string. h> # include <string> # include <limits. h> # include <algorithm> # include <math. h> # include <numeric> # include <functional> # include <ctype. h> using namespace STD; const int Kmax = 10010; const double Keps = 10e-6; int num [Kmax]; int binsearch (const int * array, const Int & N, const Int & Key) {int L = 0, r = n-1, t =-1; while (L <= r) {int mid = L + (R-l)> 1 ); if (array [l] <= array [Mid] & array [l] <= Key & Key <= array [Mid] | array [l]> array [Mid] & (array [l] <= Key | key <= array [Mid]) {T = mid; R = mid-1;} elsel = Mid + 1;} If (t =-1) return t; else return (array [T] = Key )? T:-1;} int main (void) {# ifdef debug freopen (".. /stdin.txt "," r ", stdin); freopen (".. /stdout.txt "," W ", stdout); # endif int N, key; CIN> N; For (INT I = 0; I <n; ++ I) cin> num [I]; CIN> key; printf ("% d \ n", binsearch (Num, N, key); Return 0 ;}

Input example:

14
10 11 12 13 14 1 2 3 4 5 6 7 8 9
5

Related Article

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.