查找算法

查找:所谓查找就是在数据集合中寻找满足某种条件的数据元素。

1. 二分查找

1.1 二分查找的定义

二分查找也属于顺序表查找范围,二分查找也称为折半查找。二分查找(有序)的时间复杂度为O(LogN)。

那么什么是二分查找呢?二分查找的基本思想是, 在有序表中,取中间记录作为比较对象,若给定值与中间记录的关键字相等,则查找成功;若给定值小于中间记录的关键字,则在中间记录的左半区继续查找;若给定值大于中间记录的关键字,则在中间记录的右半区继续查找。不断重复上述过程,直到找到为止。

从二分查找的定义我们可以看出,使用二分查找有两个前提条件:

1,待查找的列表必须有序。

2,必须使用线性表的顺序存储结构来存储数据。

1.2 二分查找的算法实现

(1) 递归实现

int BinarySearchRecursive(int* a, int start,int end, int goal)
{
    if (a == nullptr || start < 0||end<start)
    {
        std::cerr << "序列为空或没有查找到"<<std::endl;
        return -1;
    }
    int midIndex = (start + end) / 2;
    if (goal == a[midIndex])
        return midIndex;
    if (goal < a[midIndex])
        return BinarySearchRecursive(a, start, midIndex - 1, goal);
    else if (goal>a[midIndex])
        return BinarySearchRecursive(a, midIndex + 1, end, goal);
}

(2) 循环实现

int BinarySearch(int* a, int start, int end, int goal)
{
    if (a == nullptr || start < 0 || end < start)
    {
        std::cerr << "序列为空" << std::endl;
        return -1;
    }
    while (start<=end)
    {
        int midIndex = (start + end) / 2;
        if (goal == a[midIndex])
            return midIndex;
        if (goal < a[midIndex])
            end = midIndex - 1;
        else
            start = midIndex + 1;
    }
    return -1;//没有找到
}

(3) 实例测试

// BinaryTree.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "BinaryTree.h"
#include "search.h"
#include <cstdlib>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    //int a[] = { 0,0,0,1 };
    std::cout << BinarySearchRecursive(a, 0,9,10);
    system("pause");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值