內插搜尋法又叫插補搜尋法, 是二分搜尋法的改良版. 它是依照資料位置的分佈, 利用公式預測資料的所在位置, 再以二分法的方式漸漸逼近. 使用內插法是假設資料平均分布在陣列中, 而每一筆資料的差距是相當接近或是有一定的距離比例. 其內插法的公式為 :
Mid = low + ((key-data[low])) / (data[high] - data[low])) * (high - low)
其中 key 是要找尋的鍵, data[high], data[low] 是剩餘待找尋紀錄中的最大值與最小值, 對資料筆數 n , 其插補搜尋法的步驟如下 :
內插法分析 :
範例代碼 :
- #include
- #include
- #include
- #include
- using namespace std;
- struct BenchMark {
- int swapTime; // Swap Time
- int verifyTime; // Verify Time
- double cTime; // Consumed Time
- };
- void _swapValue(int *a, int *b) {
- int tmp = *a;
- *a = *b;
- *b = tmp;
- }
- void quickSort(int data[], int n, int i, int j) {
- if(i >= j)
- return;
- int m=0, left=i+1, right=j;
- int cnt=0, vt=0;
- while(left
- vt++;
- if(data[left]<=data[i]) {
- left++;
- continue;
- }
- vt++;
- if(data[right]>=data[i]) {
- right--;
- continue;
- }
- _swapValue(&data[left], &data[right]);
- cnt++;
- left++;
- right--;
- }
- if(data[i]
- right--;
- }
- _swapValue(&data[i], &data[right]);
- quickSort(data, n, i, right-1);
- quickSort(data, n, right+1, j);
- }
- int interSearch(int data[50], int val) {
- int low=0, mid, high=49;
- int tmpLow, tmpHigh;
- cout << "搜尋處理中(使用內插搜尋法)..." << endl;
- if(val <= data[high] && val >= data[low]) {
- while(low<=high && val !=-1) {
- tmpLow = low; tmpHigh = high;
- if(val == data[high]) return high;
- if(val == data[low]) return low;
- if(data[low]>val || data[high]
break; - printf("Current low=%d, high=%d...\t", low, high);
- mid = low + ((val - data[low]) * (high - low) / (data[high] - data[low]));
- printf("Using mid=%d\n", mid);
- if (data[mid] > val) {
- high = mid - 1;
- } else if(data[mid] < val) {
- low = mid + 1;
- } else if(data[mid] == val) {
- return mid;
- }
- if(tmpLow == low && tmpHigh == high) {
- printf("low=%d with data[low]=%d\n", low, data[low]);
- printf("high=%d with data[high]=%d\n", high, data[high]);
- printf("mid=%d with data[mid]=%d\n", mid, data[mid]);
- system("pause");
- }
- }
- }
- return -1;
- }
- void main() {
- int data[50] = {0}, val=1;
- for(int i=0; i<50; i++) {
- data[i] = val;
- val+=(rand()%5+1);
- }
- quickSort(data, 50, 0, 49); // 內插搜尋法的資料必須排序過. 這裡使用快速排序法
- int key=0, num;
- while(1) {
- cout << "請輸入搜尋值(1-150), 輸入-1結束: ";
- cin >> key;
- if(key<0)
- break;
- num = interSearch(data, key);
- if(num>=0) {
- cout << "在第 " << num << "個位置找到 ( data[" << num << "]=" << data[num] << "." << endl;
- } else {
- cout << "##### 沒有找到 " << key << "#####" << endl;
- }
- }
- }
沒有留言:
張貼留言