大家好,又见面了,我是全栈君。
该阵列是按升序排列,通过循环数组后动。肯定是有左半或半或升序的一部分。
代码:
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
版权声明:本文博客原创文章,博客,未经同意,不得转载。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/117323.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有