排序算法
二分查找
用于有序元素列表的查找
性能:
| 時間復(fù)雜度 | 空間復(fù)雜度 |
|---|---|
| O (log n ) |
- Python實現(xiàn):
def binary_search(list, item):
'''二分查找
list:數(shù)組列表
item:要查詢的值
'''
num=0
low_index = 0
high_index = len(list)-1
while low_index <= high_index:
num+=1
mid = (low_index + high_index)//2
guess = list[mid]
if guess == item:
return "的索引為"+str(mid)+",查詢次數(shù)為"+str(num)
if guess > item:
high_index = mid - 1
else:
low_index = mid + 1
return "值在數(shù)組中不存在,查詢次數(shù)為"+str(num)
- C#實現(xiàn)
/// <summary>
/// 二分查找每個數(shù)
/// </summary>
/// <returns></returns>
public static string Binary_search(int[] list, int item)
{
var num = 0;
var low_index = 0;
var high_index = list.Length - 1;
while (low_index <= high_index)
{
num += 1;
var mid = (low_index + high_index)/2;
var guess = list[mid];
if (guess == item)
{
return $"的索引為{mid}查詢次數(shù)為{num}";
}
else if (guess > item)
{
high_index = mid - 1;
}
else
{
low_index = mid + 1;
}
}
return $"值在數(shù)組中不存在,查詢次數(shù)為{num}";
}