3.18二分搜索算法各种变种
来源:互联网 发布:王传君我不喜欢知乎 编辑:程序博客网 时间:2024/06/05 11:27
编程之美3.18后面的二分查找题解:
#include<stdlib.h>#include<stdio.h>//最大索引,等于kint bisearch(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex < maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] <= v) minIndex = midIndex;else maxIndex = midIndex - 1;}if (arr[maxIndex] == v) return maxIndex;else if (arr[minIndex] == v) return minIndex;else return -1; }//任意一个等于V的索引int bisearch2(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex <= maxIndex){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] == v) return midIndex;else if (arr[midIndex] < v) minIndex = midIndex + 1;else maxIndex = midIndex - 1;}return -1;}//最小索引,等于kint bisearch3(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex < maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] >= v) maxIndex = midIndex;else minIndex = midIndex + 1;}if (arr[minIndex] == v) return minIndex;else if (arr[maxIndex] == v) return maxIndex;return -1;}//最小的索引,大于kint bisearch4(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex <= maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] > v) maxIndex = midIndex;else minIndex = midIndex + 1;}if (arr[maxIndex] > v) return maxIndex;return -1;}//最大的索引,小于kint bisearch5(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex < maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] >= v) maxIndex = midIndex - 1;else minIndex = midIndex;}if (arr[maxIndex] < v) return maxIndex;if (arr[minIndex] < v) return minIndex;return -1;}int main(){int arr[] = {1,2,3,4,5,5,5,6,6,7,8,9,9};int k;while(1){scanf("%d",&k);printf("%d,%d\n",sizeof(arr)/sizeof(arr[0]),bisearch5(arr, 0, sizeof(arr)/sizeof(arr[0]) - 1,k));}return 0;}
- 3.18二分搜索算法各种变种
- 二分查找算法及其变种
- 二分查找算法及其变种
- 算法 二分查找的变种以及注意事项
- 【基础算法】搜索-二分搜索
- 数据结构与算法之二分查找法及其变种
- C#二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 简单算法--二分搜索
- 二分搜索算法细节
- 研究二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 二分搜索算法
- Nmap参考指南
- POI操作Excel常用方法总结
- C++ FAQ学习笔记 26章 内置原始类型等
- 分层与解耦
- cygwin unable to allocate heap
- 3.18二分搜索算法各种变种
- Cisco Type 7 Password 加密解密原理和代码
- 关于C++中的 多态 问题
- SQLServer语句运行统计信息
- cisco “env_vars” file on flash
- .net 注册帐号时邮箱激活
- Android网络编程之Http通信
- Android入门之Fragment和FragmentActivity的使用方法
- jQuery选择器的灵活用法