怎么都被用过了 发表于 2015-8-9 10:16:11

谢谢小甲鱼

千秋雪 发表于 2016-9-18 16:56:24

/*
**折半查找法--递归实现
**2016年9月18日 15:44:02
*/

#include <stdio.h>


int main()
{
        int data = {1, 1, 2, 3, 5 ,8, 13, 21, 34, 55, 89, 144, 233, 377, 610};
        int e, index;
        printf("请输入待查找的元素:\n");
        scanf("%d", &e);
        index = half_search(data, e, 0, 14);       
        if(index != -1)
                printf("查找成功! 元素%d在数组中的下标为%d\n", e, index);
        else
                printf("查找失败! 元素%d不在数组中\n");
        return 0;
}

//折半查找法--递归实现
int half_search(int *data, int e, int low, int high)
{
        if(low > high)
                return -1;
        int mid = (low + high) / 2;
        if(e > data)
                return half_search(data, e, mid + 1, high);
        else if(e < data)
                return half_search(data, e, low, mid - 1);
        else
                return mid;
}

lwzzuiniubi 发表于 2018-5-7 21:36:48

来喵一眼递归实现。。。。。。。。。。。

xypmyp 发表于 2019-6-9 13:30:00

#include <stdio.h>
#include <stdlib.h>

int fnBinarySearch(int*, int*, int);
int iArray = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };

int main(void) {
        int iSearch = 0, iAnswer = 0;
        int* piArray_Low = iArray, *piArray_High = iArray + 9;

        printf("Search for:\n");
        scanf_s("%d", &iSearch);

        iAnswer = fnBinarySearch(piArray_Low, piArray_High, iSearch);
        if (iAnswer > 0) printf("[%d]\n\n", iAnswer);
        else printf("No Found!\n\n");

        system("pause");
        return 0;
}

int fnBinarySearch(int* piMin, int* piMax, int iSearch) {
        int iOffset = (piMax - piMin) / 2, iGuess = *(piMin + iOffset), iTempOffset = 0;

        if (iOffset == 0) return -1;

        if (iGuess < iSearch) piMin = piMin + iOffset + 1;
        else if (iGuess > iSearch) piMax = piMin + iOffset - 1;
        else return -(iArray - (piMin + iOffset) - 1);
        return fnBinarySearch(piMin, piMax, iSearch);
}

最后的魁拔 发表于 2020-4-16 14:58:34

#include <iostream>
using namespace std;
int find(int a[],int left,int key,int right);
int main(void)
{
    int num[]={1,2,3,4,5,6,7,8,9,10};
    int index = find(num,0,10,10);

    printf("%d\n",index);

    system("pause");
    return 0;
}

int find(int a[],int left,int key,int right)
{
    int mid;
    mid = (left+right-1)/2;
    if(left>right)
      return -1;
    if(a==key)
      return mid;
    if(a<key)
      return find(a,left=mid+1,key,right);
    if(a>key)
      return find(a,left,key,right=mid-1);
   
}
页: 1 [2]
查看完整版本: 折半查找法(递归实现)