Search algorithm-------interpolation search

Interpolation lookup

Then we found our last search method, binary search will become troublesome if you look up some numbers. For a simple example, we have 1, 2, 3, 4, 5, 6, 7 and we search 1 and we will find that we will search 3 times , A bit unsatisfactory, so do we have a more efficient method?

principle

1. The interpolation search algorithm is similar to the binary search , the difference is that the interpolation search starts from the adaptive mid each time .
2. The formula for finding the mid index in the half search, low represents the left index, and high represents the right index.

Insert picture description here

key is the value we want to find findValue

3.int midlIndex = low + (high - low) * (key - arr[|ow])/ (arr[high] - arr[|ow])

The corresponding code becomes

int mid = left + (right - left) * (findValue-arr[left])/(arr[right] - arr[left])

Examples and ideas

Find in an array of 1-100

Ideas

In the traditional method, mid=99/2=49, which is the 50th number to start searching

But now we need to find the value if it is 1.

Using binary search, we need to recurse multiple times to find the number 1

If we are using the interpolation search algorithm, our mid=0

If the search is 100, then our mid=0+99*99/99=99

Code

//插值查找
//@author 王
//2021年1月19日21:14:32
public class InsertValueSearch {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int arr[] = new int[100];
		for (int i = 0; i < 100; i++) {
    
    
			arr[i] = i+1;
		}
		int index = insertValueSearch(arr, 0, arr.length-1,3);
		System.out.println(index);
	}
	//插值查找算法
	/**
	 * 
	 * @param arr 			数组
	 * @param left			左边索引
	 * @param right			右边索引
	 * @param findValue		需要找的值
	 * @return
	 */
	public static int insertValueSearch(int[] arr,int left,int right,int findValue) {
    
    
		System.out.println("统计查找次数");
		if(left > right || findValue < arr[0] || findValue > arr[arr.length-1]){
    
    
			return -1;
		}
		//求出mid
		int mid = left + (right - left) * (findValue - arr[left])/(arr[right] - arr[left]);
		int midValue = arr[mid];
		if(findValue > midValue){
    
    
			//向右边递归
			return insertValueSearch(arr, mid+1, right, findValue);
		}else if(findValue < midValue){
    
    
			//向左边查找
			return insertValueSearch(arr, left, mid - 1, findValue);
		}else{
    
    
			return mid;
		}
	}
}

Precautions

1. For lookup tables with a large amount of data and relatively uniform keyword distribution , interpolation search is faster.
2. In the case of uneven keyword distribution , this access method is not necessarily better than half search , sometimes Is also more optimized

We can compare the array and search methods in the algorithms written in my previous blogs, and we will understand

Guess you like

Origin blog.csdn.net/qq_22155255/article/details/112852834