问题描述
小明在图书馆借阅书籍,图书馆的书籍在系统中按序号顺次排列,小明在借阅后,需在系统中从“在馆书籍列表”中将该书删除。请帮助小明编写一个函数,在现有列表{1, 3, 5, 6, 7, 10, 12, 14, 26, 32, 35, 39, 42, 45, 54, 56, 69, 73, 75, 80, 82, 86, 89, 94, 98, 100, 104, 132, 148, 150}中使用二分查找的方法找到该图书序号,若在列表中,将该序号删除,返回“Book borrowing successful”;若不在列表中,则删除失败,返回“Book borrowing failed”。
输入描述
第一行输入一个整数n,表示借阅书籍本数。
第二行输入n个数字,依次为借阅书籍的序号。
输出描述
输出删除结果,“Book borrowing successful”或“Book borrowing failed”
样例输入
2 54 103
样例输出
Book borrowing successful Book borrowing failed
#include<stdio.h>
int L[] = {1, 3, 5, 6, 7, 10, 12, 14, 26, 32, 35, 39, 42, 45, 54, 56, 69, 73, 75, 80, 82, 86, 89, 94, 98, 100, 104, 132, 148, 150};
int length = sizeof(L) / sizeof(L[0]); //计算列表长度
int BinSearch(int key) //二分查找
{int left = 0, right = length - 1;while (left <= right){int mid = (left + right) / 2;if (L[mid] < key)left = mid + 1;else if (L[mid] > key)right = mid - 1;elsereturn mid;}return -1; //查找失败
}
void delete_book(int index) //删除列表元素
{for (int i = index; i < length - 1; i++) {L[i] = L[i + 1];}length--;
}
int main()
{int n = 0;scanf("%d", &n);for (int i = 0; i < n; i++){int key = 0;scanf("%d", &key);int k = BinSearch(key);if (k != -1){delete_book(k);printf("Book borrowing successful\n");}elseprintf("Book borrowing failed\n");}return 0;
}