C経典二分検索法


1.keyに基づいて配列の位置を検索する
#include <stdio.h>
/* key = 9; 1 2 3 4 5 6 7 8 arr 3, 4, 5, 7, 9 , 11, 21, 23 low = 1 mid = (low + high)/2 = 4 high = 8; one arr[mid] = 7 < 9; so low = mid + 1 = 5; high = 8; mid = (low + high)/2 = 6 two arr[mid] = 11 > 9 so low = 5 , high = mid - 1 = 5 mid = 5; arr[mid] = 9 == key if(key = 10) low = mid + 1 > high */
int main(int argc, const char * argv[])
{
    int findByHalf(int arr[], int len, int key);

    int arr[] = {3, 4 ,  5, 7, 9 , 11, 21, 23};
    int len = sizeof(arr)/sizeof(int);

    int index = findByHalf(arr, len, 88);

    printf("index = %d
"
, index); return 0; } int findByHalf(int arr[], int len, int key){ int low = 0; int high = len - 1; int mid ; while(low <= high){ mid = (low + high) / 2; // if (key > arr[mid]) { low = mid + 1; // }else if (key > arr[mid]) { high = mid - 1; }else{ return mid; } } return -1; }

2.数を挿入し、その配列の位置を得る
#include <stdio.h>
/* key = 9; 1 2 3 4 5 6 7 8 arr 3, 4, 5, 7, 9 , 11, 21, 23 low = 1 mid = (low + high)/2 = 4 high = 8; one arr[mid] = 7 < 9; so low = mid + 1 = 5; high = 8; mid = (low + high)/2 = 6 two arr[mid] = 11 > 9 so low = 5 , high = mid - 1 = 5 mid = 5; arr[mid] = 9 == key if(key = 10) low = mid + 1 > high */
int main(int argc, const char * argv[])
{
    int findByHalf(int arr[], int len, int key);

    int arr[] = {3, 4 ,  5, 7, 9 , 11, 21, 23};
    int len = sizeof(arr)/sizeof(int);

    int index = findByHalf(arr, len, 88);

    printf("index = %d
"
, index); return 0; } int insertByHalf(int arr[], int len, int key){ int low = 0; int high = len - 1; int mid ; while(low <= high){ mid = (low + high) / 2; // if (key > arr[mid]) { low = mid + 1; // }else if (key > arr[mid]) { high = mid - 1; }else{ // arr[mid] == key // key return mid + 1; } } // low > high key > arr[mid]; // key low return low; }