码迷,mamicode.com
首页 > 编程语言 > 详细

查找算法

时间:2015-07-27 18:55:46      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:二分法查找

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

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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

查找算法

标签:二分法查找

原文地址:http://blog.csdn.net/u010177286/article/details/47088079

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!