王道数据结构 (13) 折半查找

 

 

 

伪代码:

 

 

可运行代码:

#include <stdio.h>
binarySearch(int a[], int n, int key)
{
  int low = 0;
  int high = n - 1;
  while (low <= high)
  {
    int mid = (low + high) / 2;
    int midVal = a[mid];
    printf("%d", mid);
    printf("中间值 \n");
    if (midVal < key)
      low = mid + 1;
    else if (midVal > key)
      high = mid - 1;
    else
      return mid;
  }
  return -1;
}
int main()
{
  int i, val, ret;
  int a[8] = {-32, 12, 16, 24, 36, 45, 59, 98};
  for (i = 0; i < 8; i++)
    printf("%d\t", a[i]);
  printf("\n请输人所要查找的元素:");
  scanf("%d", &val);
  ret = binarySearch(a, 8, val);
  if (-1 == ret)
    printf("查找失败 \n");
  else
    printf("查找成功 \n");
  return 0;
}

结果:

 

 

 

代码:

/*
 * @Author: your name
 * @Date: 2020-08-11 13:44:12
 * @LastEditTime: 2020-08-11 13:53:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \C-data-structure\折半查找\折半查找.c
 */
#include <stdio.h>
binarySearch(int a[], int n, int key)
{
  int low = 0;
  int high = n - 1;
  while (low <= high)
  {
    int mid = (low + high) / 2;
    int midVal = a[mid];
    printf("%d", mid);
    printf("中间值 \n");
    if (midVal < key)
      low = mid + 1;
    else if (midVal > key)
      high = mid - 1;
    else
      return mid;
  }
  return -1;
}
int main()
{
  int i, val, ret;
  int a[11] = {7, 10, 13, 16, 19, 29, 32, 33, 37, 41, 43};
  for (i = 0; i < 8; i++)
    printf("%d\t", a[i]);
  printf("\n请输人所要查找的元素:");
  scanf("%d", &val);
  ret = binarySearch(a, 8, val);
  if (-1 == ret)
    printf("查找失败 \n");
  else
    printf("查找成功 \n");
  return 0;
}

运行:

 

 

 

 

 

 

posted @ 2020-08-11 13:45  1点  阅读(294)  评论(0编辑  收藏  举报