1、顺序查找(无序)
2、折半查找(必须是有序数组)
实现代码(java)
public class lineSearch {
//测试代码
public static void main(String[] args) {
//顺序查找
int[] arr1 = {34,76,23,98,87,35,8,32,74,44};
int key = 8;
System.out.println(key+"出现的索引为:"+search(arr1,8));//6
//二分法查找(有序数组)
int[] arr2 = {1,2,3,4,5,6,7,8,9,10};
//非递归方式
System.out.println(key+"出现的索引为:"+myBinarySearch(arr2,8));//7
//递归方式
System.out.println(key+"出现的索引为:"+myBinarySearch2(arr2,8));//7
}
/**
* 时间复杂度:T(n) = O(logn)
* 空间复杂度:S(n) = O(logn)
* 递归二分法查找
* @param arr
* @param key
* @return
*/
private static int myBinarySearch2(int[] arr, int key) {
int low = 0;
int high = arr.length;
return binarySearch(arr,key,low,high);
}
//递归方法
private static int binarySearch(int[] arr, int key,int low,int high) {
int mid = (low+high)/2;
if(key == arr[mid]){
return mid;
}else if(key < arr[mid]){
return binarySearch(arr,key,low,mid -1);
}else if(key > arr[mid]){
return binarySearch(arr,key,mid+1,high);
}
return -1;
}
/**
* 时间复杂度: T(n) = O(logn)
* 空间复杂度:S(n) = O(1)
* 非递归二分法查找
* @param arr
* @param key
* @return
*/
private static int myBinarySearch(int[] arr, int key) {
int low = 0;
int high = arr.length;
int mid = 0;
while(low<=high){
mid = (high + low)/2;
if(key == arr[mid]){
return mid;
}else if (key<arr[mid]){
high = mid - 1;
}else{
low = mid + 1;
}
}
return -1;
}
/**
* 时间复杂度:T(n) = O(n)
* 空间复杂度:S(n) = O(1)
* 顺序查找
* @param arr
* @param key
* @return
*/
private static int search(int[] arr, int key) {
if(arr == null || arr.length ==0){
return -1;
}
for(int i = 0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
}