zoukankan      html  css  js  c++  java
  • 但是,在通过移动数组的上升周期中找到指定元素

    该阵列是按升序排列,通过循环数组后动。肯定是有左半或半或升序的一部分。

    代码:

    public class SearchRotateArray {
    	public static int search(int a[], int l, int u, int x) {
    		while(l<=u){
    			int m = (l+u)/2;
    			if(x==a[m]){
    				return m;
    			}else if(a[l]<=a[m]){ //左半部分升序排列
    				if(x>a[m]){
    					l=m+1;
    				}else if(x>=a[l]){
    					u=m-1;
    				}else{// x<a[l]
    					l=m+1;
    				}
    			}else if(a[l]>a[m]){ //右半部分升序
    				if(x>a[u]){
    					u=m-1;
    				}else if(x>=a[m]){
    					l=m+1;
    				}else{ //x<a[m]
    					u=m-1;
    				}
    			}
    		}
    		return -1;
    	}
    	
    	
    	public static void main(String[] args){
    		int a[] = {15,16 ,19, 20, 25, 1, 3, 4, 5, 7, 10, 14};
    		System.out.println(search(a, 0, a.length - 1, 5));
    	}
    }

    结果:

    8

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    155. 最小栈
    160. 相交链表
    PAT 1057 Stack
    PAT 1026 Table Tennis
    PAT 1017 Queueing at Bank
    PAT 1014 Waiting in Line
    PAT 1029 Median
    PAT 1016 Phone Bills
    PAT 1010 Radix
    PAT 1122 Hamiltonian Cycle
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4716359.html
Copyright © 2011-2022 走看看