C#折半查找和插值查找

折半查找适用于有序表。

int binSearch(int[] a, int key)
{
  int low = 0;
  int high = a.Length-1;
  int mid;
  while(low <= high)
  {
    mid = (low + high) / 2;
    if(a[mid] == key)
      retrun mid;
    else(a[mid] < key)
      low = mid + 1;
    else
      high = mid - 1;
  }
  return -1;
}

插值查找是对折半查找的改进
通过计算key距离low比较近还是距离high比较近,提高查找效率。

int binSearch(int[] a, int key)
{
  int low = 0;
  int high = a.Length-1;
  int mid;
  while(low <= high)
  {
    mid =low +(key - a[low]) / (a[high] - a[low]) * (high - low);
    if(a[mid] == key)
      retrun mid;
    else(a[mid] < key)
      low = mid + 1;
    else
      high = mid - 1;
  }
  return -1;
}

你可能感兴趣的:(C#)