using UnityEngine;
using System.Collections;
//二分查找
public class BinarySearch : MonoBehaviour
{
int index;
void Start()
{
if (Search(2, ref index))
Debug.Log(index);//返回索引
print(Res(2, array, 0, 4));
}
int[] array = new int[] { 2, 3, 4, 5, 6 };
//普通方法
bool Search(int value, ref int result)
{
int start = 0;
int end = array.Length - 1;
int mid;
while (start <= end)
{
mid = (start + end) / 2;
if (array[mid] == value)
{
result = value;
return true;
}
else if (array[mid] < value)
{
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return false;
}
//递归方法
//要查询的值,要查询的数组,开始下标,介绍下标
bool Res(int value, int[] array, int start, int end)
{
if (start > end) return false;
int mid = (start + end) / 2;
if (array[mid] == value)
{
return true;
}
else if (array[mid] < value)
{
return Res(value, array, mid + 1, end);
}
else
{
return Res(value, array, start, mid - 1);
}
}
}