线性查找
//线性查找,找到一个满足条件的值就返回
public static int seqSearch(int[] arr,int value){
//线性查找是逐一比对,发现有相同值,就返回下标
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
return i;
}
}
return -1;
}
二分查找
public static int binarySearch(int[] arr,int left,int right,int value){
if (left > right) {
return -1;
}
int mid = (left+right)/2;
int midVal = arr[mid];
if (value>midVal){//向右递归
return binarySearch(arr,mid+1,right,value);
} else if (value < midVal) {
return binarySearch(arr,left,mid-1,value);
}else {
return mid;
}
}
public static ArrayList binarySearch2(int[] arr, int left, int right, int value){
if (left > right) {
return null;
}
int mid = (left+right)/2;
int midVal = arr[mid];
if (value>midVal){//向右递归
return binarySearch2(arr,mid+1,right,value);
} else if (value < midVal) {
return binarySearch2(arr,left,mid-1,value);
}else {
ArrayList<Integer> list = new ArrayList<Integer>();
int temp = mid-1;
while (true){
if (temp<0||arr[temp]!=value){//退出
break;
}
list.add(temp);
temp-=1;
}
list.add(mid);
temp = mid+1;
while (true) {
if (temp > right || arr[temp] != value) {
break;
}
list.add(temp);
temp+=1;
}
return list;
}
}
差值查找
public static int insertValueSearch(int[] arr,int left,int right,int value){
if (left > right || value<arr[0]||value>arr[arr.length-1]) {
return -1;
}
int mid = left+(right-left)*(value-arr[left])/(arr[right]-arr[left]);
int midValue = arr[mid];
if (value > midValue) {
return insertValueSearch(arr,mid+1,right,value);
} else if (value < midValue) {
return insertValueSearch(arr,left,mid-1,value);
} else {
return mid;
}
}