二分法查找用于大小有序数组,对于包含n个元素的列表,找到目标值最多只需要
L
o
g
2
n
Log{_{2}}^{n}
Log2n步,而简单查找需要n步。
举例,从数组中找出45在数组的索引,数组中没有45则返回-1:
using UnityEngine;
public class BinarySearch : MonoBehaviour
{
[ContextMenu("Do")]
private void Do()
{
int[] arr = { 3,4,5,6,12,14,16,17,34,45,72};
int index = IndexOf(45, arr);
Debug.Log("index of : "+index);
}
/// <summary>
/// 二分法查找,从有序数组中找到value的索引,没找到则返回-1
/// </summary>
private int IndexOf(int value, int[] arr) {
int low = 0;
int high = arr.Length - 1;
while (low < high) {
int mid = low + (high - 1)/2;
if (value < arr[mid])
{
high = mid - 1;
}
else if(value > arr[mid])
{
low = mid + 1;
}else{
return mid;
}
}
return -1;
}
}