您的位置:首页 > 其它

查找--二分查找

2016-06-23 15:41 369 查看
二分查找的前提是线性表中的记录必须是有序的,线性表必须采用顺序存储。

二分查找的基本思想是:

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: