欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用二分法查找有序数组中某一元素

程序员文章站 2022-03-13 23:26:56
...
1.利用二分法查找有序数组中某一元素,若有,返回下标,若没有,返回-1。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//int binary_search(int* a, int k)
int binary_search(int a[], int k, int sz)
{
 int left = 0;
 int right = sz - 1;
 while (left <= right)
 {
  int mid = right - (right - left) / 2;
  if (a[mid] == k)
  {
   return mid;
  }
  else if (a[mid] > k)
  {
   right = mid - 1;
  }
  else
  {
   left = mid + 1;
  }
 }
 return -1;
}
int main()
{
 int arr[] = { 1,2,3,4,5,6,7,8,9 };
 int key = 6;
 int sz = sizeof(arr) / sizeof(arr[0]);
 int ret = binary_search(arr, key, sz);
 if (-1 == ret)
  printf("找不到\n");
 else
  printf("找到了:%d\n", ret);
 system("pause");
 return 0;
}
2.猜数字游戏

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
void menu()
{
 printf("********   1.play   0.exit    ********\n");
}
void game()
{
 int num = 0;
 int input = 0;
 num = rand()%100+1;
 //printf("%d\n", num);
 while (1)
 {
  printf("请猜数字:>");
  scanf_s("%d", &input);
  if (num == input)
  {
   printf("恭喜你,猜对了\n");
   break;
  }
  else if (input < num)
  {
   printf("猜小了\n");
  }
  else
  {
   printf("猜大了\n");
  }
 }
}
int main()
{
 srand((unsigned int)time(NULL));
 int input = 0;
 do
 {
  menu();
  printf("请选择:>");
  scanf_s("%d", &input);
  switch (input)
  {
  case 1:
   game();
    break;
  case 0:
   printf("退出游戏\n");
   break;
  default:
   printf("选择错误\n");
   break;
  }
 } 
 while (input);
return 0;
}
3.模拟三次输入密码的场景

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
 int time = 3;
 char password1[] = "123456";
 char password2[10] = {0};
 while(time)
 {
  printf("请输入密码:>");
  scanf_s("%s", &password2);
  if (strcmp(password1, password2) == 0)
  {
   printf("登录成功\n");
   break;
  }
  else
  {
   ;
  }
  time--;
 }
 if (time == 0)
 {
  printf("密码已输入三次错误,退出登录\n");
 }
 system("pause");
 return 0;
}