算法(四):二分法查找

先排序,后查找


middle = (1eft+right)/2;

target > middle, find right

target < middle, find left

target == middle, find target


root@ubuntu:/mnt/shared/appbox/bisearch# cat bisearch.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int issort(int *array, int num)
{
        int i, j, tmp;

        for(j=1; j<num; j++)
        {
                tmp = array[j];
                i = j - 1;
                while( i >= 0 && array[i] > tmp)
                {
                        array[i+1] = array[i];
                        i--;

                }
                array[i+1] = tmp;
        }
        return 0;
}


static int compare_int(const void *int1, const void *int2)
{
        if(*(const int *)int1 == *(const int *)int2)
                return 0;

        return *(const int *)int1 > *(const int *)int2 ? 1 : -1;
}


int bisearch(void *sorted, const void *target, int size, int esize, int (*compare)(const void *key1, const void *key2))
{
        int left, middle, right;

        left = 0;
        right = size -1;

        while(left <= right)
        {
                middle = (left+right)/2;
                switch(compare(&((int *)sorted)[middle], target))
                {
                        case -1://target > middle, search right half
                                left = middle + 1;
                                break;
                        case 1: // target < middle, search left half
                                right = middle -1;
                                break;
                        case 0:
                                return middle;
                }
        }
        return -1;
}

int main(int argc, char *argv[])
{
        int i;
        int target = 77;
        int index;
        int a[10] = {1,44,22,77,11,7,4,88,78, 102};

        issort(a, 10);

        for(i=0; i<10; i++)
        {
                printf("%d,", a[i]);
        }

        printf("\n");

        index = bisearch(a, &target, 10, 4, compare_int);
        printf("index of %d is:%d\n", target, index);

        return 0;
}
结果:

root@ubuntu:/mnt/shared/appbox/bisearch# ./bisearch    
1,4,7,11,22,44,77,78,88,102,
index of 77 is:6

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