Data-structures-algorithms-interpolation-search-in-c

提供:Dev Guides
移動先:案内検索

Cの内挿検索プログラム

補間検索は、バイナリ検索の改良版です。 この検索アルゴリズムは、必要な値の調査位置で機能します。 このアルゴリズムが適切に機能するためには、データ収集がソートされ、均等に分散された形式である必要があります。

実行時の複雑さは* log [.small] 〜2〜(log [.small] 〜2〜 n)*です。

Cでの実装

#include<stdio.h>

#define MAX 10

//array of items on which linear search will be conducted.
int list[MAX] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };

int find(int data) {
   int lo = 0;
   int hi = MAX - 1;
   int mid = -1;
   int comparisons = 1;
   int index = -1;

   while(lo <= hi) {
      printf("\nComparison %d  \n" , comparisons ) ;
      printf("lo : %d, list[%d] = %d\n", lo, lo, list[lo]);
      printf("hi : %d, list[%d] = %d\n", hi, hi, list[hi]);

      comparisons&plus;&plus;;

     //probe the mid point
      mid = lo &plus; (((double)(hi - lo)/(list[hi] - list[lo])) * (data - list[lo]));
      printf("mid = %d\n",mid);

     //data found
      if(list[mid] == data) {
         index = mid;
         break;
      } else {
         if(list[mid] < data) {
           //if data is larger, data is in upper half
            lo = mid &plus; 1;
         } else {
           //if data is smaller, data is in lower half
            hi = mid - 1;
         }
      }
   }

   printf("\nTotal comparisons made: %d", --comparisons);
   return index;
}

int main() {
  //find location of 33
   int location = find(33);

  //if element was found
   if(location != -1)
      printf("\nElement found at location: %d" ,(location+1));
   else
      printf("Element not found.");

   return 0;
}

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

出力

Comparison 1
lo : 0, list[0] = 10
hi : 9, list[9] = 44
mid = 6

Total comparisons made: 1
Element found at location: 7

検索値を変更し、プログラムを実行してテストできます。