1. 二分查找
输入是有序的序列。待查找元素如果存在,输出索引,如果不存在,输出-1.
//
// main.cpp
// algorithm
//
// Created by ybwang on 2019/11/5.
// Copyright © 2019 ybwang. All rights reserved.
//
#include <iostream>
//二分查找
template <typename T>
int binarySearch(T* arr, int size, const T &key){
int left = 0;
int right = size - 1;
int middle;
while(left <= right){
middle = (left + right) / 2;
if(arr[middle] == key){
return middle;
}else if(arr[middle] < key){//小了,在右边,更新左边界
left = middle + 1;
}else{
right = middle - 1;
}
}
return -1;
}
void print(int* arr, int size, int value){
int ret = binarySearch(arr, size, value);
if(ret == -1){
std::cout << value << " is not in" << std::endl;
}else{
std::cout << value << " position is " << ret << std::endl;;
}
}
int main(int argc, const char * argv[]) {
// insert code here...
int a[13] = {1,2,3,4,5,6,7,8,9,10,15,27,31};
print(a, 13, 0);
for (int i=0; i<13; i++) {
print(a, 13, a[i]);
}
print(a, 13, 32);
return 0;
}
0 is not in
1 position is 0
2 position is 1
3 position is 2
4 position is 3
5 position is 4
6 position is 5
7 position is 6
8 position is 7
9 position is 8
10 position is 9
15 position is 10
27 position is 11
31 position is 12
32 is not in
Program ended with exit code: 0