9.11 Sort and find (iii)--given a sorted array containing n integers, but this array has been rotated several times to find an element in the array

Source: Internet
Author: User

/*** Function: Given a sorted array, containing n integers, but this array has been rotated several times, the number of times is unknown. Find an element in the array. * You can assume that the array elements were originally arranged in small to large order.  */

/** * Idea: The array has been rotated, then look for inflection points. * @param A * @param left * @param right * @param x: element to search * @return */public static int search (int[] a,int left,int right, int x) {int mid= (left+right)/2;if (X==a[mid])//Find element return Mid;if (left>right) return-1;if (A[left]<a[mid]) {// The left half is the normal order if (X>=a[left]&&x<=a[mid]) {return search (a,left,mid-1,x);//Search the left half}else{return searches (A, mid+1 }}else if (A[mid]<a[right]) {//Right half is normal order if (X>=a[left]&&x<=a[mid]) {return Search (a , left,mid-1,x);//search for left half of}else{return searches (A, mid+1, right, x);//search for Half}}else if (A[left]==a[mid]) {//left half is repeating element if (A[mid] !=a[right]) {//if the right element is different, search for the right side of the return search (A, mid+1, right, x);//search for either side of}else{//otherwise search int result=search (A, left, mid=1, X if (result==-1) {return search (A, mid+1, right, x);} Elsereturn result;}} return-1;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

9.11 Sorting and Finding (iii)--given a sorted array containing n integers, but this array has been rotated multiple times to find an element in the array

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.