查找算法

二分法查找

#include <iostream> using namespace std; void insert_sort(int a[], int len); int search_binary(int arr[], int key, int len); int main() { int intarr[6] = {3,6,2,1,23,9}; insert_sort(intarr,6); for(int i=0; i< 6; i++) cout << intarr[i] << " "; cout << endl; cout << search_binary(intarr,23,6); } void insert_sort(int a[], int len) { int insert=0; int temp = 0; for( int i=0; i< len -1; i++) { insert = i+1; while( insert && a[insert -1] > a[insert] ) { temp = a[insert]; a[insert] = a[insert -1]; a[insert -1] = temp; --insert; } } } int search_binary(int arr[], int key, int len) { int low = 0; int high = len - 1; int mid; while (low <= high) { mid = (high + low) / 2; if (arr[mid] > key) high = mid - 1; else if (arr[mid] < key) low = mid + 1; else return mid; } return -1; }

你可能感兴趣的:(查找算法)