33,311
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
using namespace std;
int BinaryS(int *source,int dest,int number); //折半查找
int main()
{
int s[12] = {1,2,3,4,5,6,7,8,9,10,11,12};
//int num = BinaryS(s,22,12);
cout << "数字11在哪个位置呢?\n";
cout << BinaryS(s,11,12) << endl;
return 0;
}
int BinaryS(int *source,int dest,int number)
{
int left = 0;
int right = number - 1;
while(left <= right)
{
int middle = (right - left)/2;
if( dest < source[middle])
right = middle - 1;
else if (dest > source[middle])
left = middle + 1;
else
//if( dest == source[middle])
return middle;
}
return -1;
}
/***
*bsearch.c - do a binary search
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines bsearch() - do a binary search an an array
*
*******************************************************************************/
#include <cruntime.h>
#include <stdlib.h>
#include <search.h>
/***
*char *bsearch() - do a binary search on an array
*
*Purpose:
* Does a binary search of a sorted array for a key.
*
*Entry:
* const char *key - key to search for
* const char *base - base of sorted array to search
* unsigned int num - number of elements in array
* unsigned int width - number of bytes per element
* int (*compare)() - pointer to function that compares two array
* elements, returning neg when #1 < #2, pos when #1 > #2, and
* 0 when they are equal. Function is passed pointers to two
* array elements.
*
*Exit:
* if key is found:
* returns pointer to occurrence of key in array
* if key is not found:
* returns NULL
*
*Exceptions:
*
*******************************************************************************/
void * __cdecl bsearch (
REG4 const void *key,
const void *base,
size_t num,
size_t width,
int (__cdecl *compare)(const void *, const void *)
)
{
REG1 char *lo = (char *)base;
REG2 char *hi = (char *)base + (num - 1) * width;
REG3 char *mid;
unsigned int half;
int result;
while (lo <= hi)
if (half = num / 2)
{
mid = lo + (num & 1 ? half : (half - 1)) * width;
if (!(result = (*compare)(key,mid)))
return(mid);
else if (result < 0)
{
hi = mid - width;
num = num & 1 ? half : half-1;
}
else {
lo = mid + width;
num = half;
}
}
else if (num)
return((*compare)(key,lo) ? NULL : lo);
else
break;
return(NULL);
}