分為:破壞性查找, 比如有一群mm,我猜她們的年齡,第一位猜到了是23+,此時(shí)這位mm已經(jīng)從我腦海里面的mmlist中remove掉了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sequential
{
class Program
{
static void Main(string[] args)
{
Listint> list = new Listint>() { 2, 3, 5, 8, 7 };
var result = SequenceSearch(list, 3);
if (result != -1)
Console.WriteLine("3 已經(jīng)在數(shù)組中找到,索引位置為:" + result);
else
Console.WriteLine("嗚嗚,沒(méi)有找到!");
Console.Read();
}
//順序查找
static int SequenceSearch(Listint> list, int key)
{
for (int i = 0; i list.Count; i++)
{
//查找成功,返回序列號(hào)
if (key == list[i])
return i;
}
//未能查找,返回-1
return -1;
}
}
}
比如"幸運(yùn)52“中的猜價(jià)格游戲,價(jià)格在999元以下,1分鐘之內(nèi)能猜到幾樣給幾樣,如果那些選手都知道折半查找,
那結(jié)果是相當(dāng)?shù)陌 ?/P>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BinarySearch
{
class Program
{
static void Main(string[] args)
{
Listint> list = new Listint>() { 3, 7, 9, 10, 11, 24, 45, 66, 77 };
var result = BinarySearch(list, 45);
if (result != -1)
Console.WriteLine("45 已經(jīng)在數(shù)組中找到,索引位置為:" + result);
else
Console.WriteLine("嗚嗚,沒(méi)有找到!");
Console.Read();
}
///summary>
/// 折半查找
////summary>
///param name="list">/param>
///returns>/returns>
public static int BinarySearch(Listint> list, int key)
{
//最低線
int low = 0;
//最高線
int high = list.Count - 1;
while (low = high)
{
//取中間值
var middle = (low + high) / 2;
if (list[middle] == key)
{
return middle;
}
else
if (list[middle] > key)
{
//下降一半
high = middle - 1;
}
else
{
//上升一半
low = middle + 1;
}
}
//未找到
return -1;
}
}
}
先前也說(shuō)過(guò),查找有一種形態(tài)是破壞性的,那么對(duì)于線性結(jié)構(gòu)的數(shù)據(jù)來(lái)說(shuō)很悲慘,因?yàn)槊看纹茐囊幌拢?/P>