查找--二分查找

二分查找的前提是线性表中的记录必须是有序的,线性表必须采用顺序存储。

二分查找的基本思想是:

1.在有序表中,取中间记录作为比较对象,若给定值与中间记录的值相等,则查找成功;

2.若给定值小于中间记录的值,则在中间记录的左半区继续查找;

3.若给定值大于中间记录的值,则在中间记录的右半区继续查找;

二分查找的时间复杂度是:O(logn)


C 版

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

#include "stdafx.h"

int binary_search(int* arr, int length, int target)
{
	int first = 0 ;
	int last = length - 1 ;
	int mid = (first + last) / 2 ;
	while (first <= last)
	{
		if (arr[mid] < target)
		{
			first = mid ;
		}
		else if (arr[mid] > target)
		{
			last = mid ;
		}
		else
		{
			return mid ;
		}
		mid = (first + last) / 2 ;
	}
	return 0 ;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int arr[] = {0, 1, 16, 24, 35, 47, 59, 62, 73, 88, 99};
	int length = 11;

	int result = binary_search(arr, length, 62);

	return 0;
}

C++ 版

// binary search c++.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
using namespace::std;

int binary_search(vector<int>& vec, int target)
{
	int first = 0 ;
	int last = vec.size() - 1 ;
	int mid = (first + last) / 2 ;
	while (first <= last)
	{
		if (vec[mid] < target)
		{
			first = mid ;
		}
		else if (vec[mid] > target)
		{
			last = mid ;
		}
		else
		{
			return mid ;
		}
		mid = (first + last) / 2 ;
	}
	return 0 ;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int arr[] = {0, 1, 16, 24, 35, 47, 59, 62, 73, 88, 99};
	vector<int> test(arr, arr + 11);

	int result = binary_search(test, 62);

	return 0;
}

C# 版

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace binary_search_CSharp
{
    class Program
    {
        static int binary_search(int[] arr, int target)
        {
            int first = 0;
            int last = arr.Length - 1;
            int mid = (first + last) / 2;
            while ( first <=  last )
            {
                if ( arr[mid] < target )
                {
                    first = mid;
                }
                else if ( arr[mid] > target )
                {
                    last = mid;
                }
                else
                {
                    return mid;
                }
                mid = (first + last) / 2;
            }
            return 0;
        }
        static void Main(string[] args)
        {
            int[] arr = { 0, 1, 16, 24, 35, 47, 59, 62, 73, 88, 99 };
            int result = binary_search(arr, 62);

            return;
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值