线性查找、二分查找和插值查找
public class Search {
public static void main(String[] args) {
int[] array = {1,3,100,100,300};
System.out.println(seqSearch(array,100));
System.out.println(binarySearch(array, 0, array.length - 1,100));
System.out.println(insertValueSearch(array, 0, array.length - 1,100));
}
public static List<Integer> seqSearch(int[] array, int findValue) {
List<Integer> indexs = new ArrayList<>();
for (int i = 0;i < array.length; i++) {
if (findValue == array[i]) {
indexs.add(i);
}
}
return indexs;
}
public static List<Integer> binarySearch(int[] array,int left, int right, int findValue) {
List<Integer> indexs = new ArrayList<>();
if (left > right) {
return indexs;
}
int mid = (left + right) / 2;
int midValue = array[mid];
if (findValue > midValue) {
return binarySearch(array, mid + 1, right, findValue);
} else if (findValue < midValue) {
return binarySearch(array, left, mid - 1, findValue);
} else {
return getList(indexs,findValue,mid, array);
}
}
public static List<Integer> insertValueSearch(int[] array,int left, int right, int findValue) {
List<Integer> indexs = new ArrayList<>();
if (left > right || findValue < array[left] || findValue > array[right]) {
return indexs;
}
int mid = left + (right - left) * (findValue - array[left]) / (array[right] - array[left]);
int midValue = array[mid];
if (findValue > midValue) {
return insertValueSearch(array, mid + 1, right, findValue);
} else if (findValue < midValue) {
return insertValueSearch(array, left, mid - 1, findValue);
} else {
return getList(indexs,findValue,mid, array);
}
}
public static List<Integer> getList(List indexs, int findValue, int mid,int[] array) {
indexs.add(mid);
int temp = mid - 1;
while (true) {
if (temp < 0 || array[temp] != findValue ) {
break;
}
indexs.add(temp);
temp--;
}
temp = mid + 1;
while (true) {
if (temp > array.length - 1 || array[temp] != findValue) {
break;
}
indexs.add(temp);
temp++;
}
return indexs;
}
}