From Gossip@caterpillar

Algorithm Gossip: 插補搜尋法

說明

如果卻搜尋的資料分佈平均的話,可以使用插補(Interpolation)搜尋法來進行搜尋,在搜尋的對象大於500時,插補搜尋法會比 二分搜尋法 來的快速。

解法

插補搜尋法是以資料分佈的近似直線來作比例運算,以求出中間的索引並進行資料比對,如果取出的值小於要尋找的值,則提高下界,如果取出的值大於要尋找的 值,則降低下界,如此不斷的減少搜尋的範圍,所以其本原則與二分搜尋法是相同的,至於中間值的尋找是透過比例運算,如下所示,其中K是指定要尋找的對象, 而m則是可能的索引值:
插補搜尋

實作

#include <stdio.h> 
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x,y) {int t; t = x; x = y; y = t;}

void quicksort(int[], int, int);
int intsrch(int[], int);

int main(void) {
int number[MAX] = {0};
int i, find;

srand(time(NULL));

for(i = 0; i < MAX; i++) {
number[i] = rand() % 100;
}

quicksort(number, 0, MAX-1);

printf("數列:");
for(i = 0; i < MAX; i++)
printf("%d ", number[i]);

printf("\n輸入尋找對象:");
scanf("%d", &find);

if((i = intsrch(number, find)) >= 0)
printf("找到數字於索引 %d ", i);
else
printf("\n找不到指定數");

printf("\n");

return 0;
}

int intsrch(int number[], int find) {
int low, mid, upper;

low = 0;
upper = MAX - 1;

while(low <= upper) {
mid = (upper-low)*
(find-number[low])/(number[upper]-number[low])
+ low;
if(mid < low || mid > upper)
return -1;

if(find < number[mid])
upper = mid - 1;
else if(find > number[mid])
low = mid + 1;
else
return mid;
}

return -1;
}

void quicksort(int number[], int left, int right) {
int i, j, k, s;

if(left < right) {
s = number[(left+right)/2];
i = left - 1;
j = right + 1;

while(1) {
while(number[++i] < s) ; // 向右找
while(number[--j] > s) ; // 向左找
if(i >= j)
break;
SWAP(number[i], number[j]);
}

quicksort(number, left, i-1); // 對左邊進行遞迴
quicksort(number, j+1, right); // 對右邊進行遞迴
}
}

public class InterpolationSearch {
public static int search(int[] number, int des) {
int low = 0;
int upper = number.length - 1;

while(low <= upper) {
int mid = (upper-low)*
(des-number[low])/(number[upper]-number[low])
+ low;
if(mid < low || mid > upper)
return -1;

if(des < number[mid])
upper = mid - 1;
else if(des > number[mid])
low = mid + 1;
else
return mid;
}

return -1;
}

public static void main(String[] args) {
int[] number = {1, 4, 2, 6, 7, 3, 9, 8};

QuickSort.sort(number);

int find = InterpolationSearch.search(number, 3);

if(find != -1)
System.out.println("找到數值於索引" + find);
else
System.out.println("找不到數值");
}
}