代码改变世界

静态查找

2011-01-20 16:29  Clingingboy  阅读(407)  评论(0编辑  收藏  举报

 

一.顺序查找

从头到尾或者从尾到头

class DataFinder
{
    static void Main()
    {
        var ints = new int[] {1, 2, 3, 6, 5, 4};
        var result1 = FindFromHead(ints, 5);
        Console.WriteLine(result1);
        var result2 = FindFromEnd(ints, 5);
        Console.WriteLine(result2);
    }

    public static int FindFromHead(int[] ints, int key)
    {
        int step = 0;

        for (int i = 0; i < ints.Length - 1; i++)
        {
            step++;
            if (ints[i] == key)
            {
                Console.WriteLine("Head step:" + step);
                return key;
            }
        }

        return -1;
    }

    public static int FindFromEnd(int[] ints,int key)
    {
        int step = 0;
        for (int i = ints.Length-1; i >0;i--)
        {
            step++;
            if (ints[i] == key)
            {
                Console.WriteLine("End step:" + step);
                return key;
            }
        }
        return -1;
    }
}

结果

image

二.折半查找(二分查找)

首先必须是有序的

public static int BinarySearch(int[] ints,int key)
{
    //don't care
    //1,2,3,4,5,6
    Array.Sort(ints);
    int step = 0;
    int low = 0, high = ints.Length - 1;
    int mid = 0;
    while (low<high)
    {
        step++;
        mid = (low + high) / 2;
        if (ints[mid] == key)
        {
            Console.WriteLine("BinarySearch step:" + step);
            return key;
        }
        if (ints[mid] > key)
            high = mid - 1;
        else
            low = mid + 1;
    }
    return -1;
}

image

此图更详细

image

分块查找(索引顺序查找)

即将数据分块,比如将1-100,分成10块,分别存储1-10,2-20…91-100.那么查找81就可以直接从第8个块开始查找.

即通过一个辅助的数组存储数组的最大索引值,先通过索引值找到块,然后根据块开始查找.

public static int BlockSearch(int key)
{
    //int
    var ints=new int[100];
    var blocks = new Block[10];
    for (int i = 1; i < 101; i++)
    {
        if (i%10 == 0)
            blocks[i / 10 - 1] = new Block() { Index = i  - 10, Value = i };
        ints[i - 1] = i;
    }
    int step = 0;
    //find Block Index First
    int index = 0;
    //21

    for (int i = 0; i < blocks.Length; i++)
    {
        step++;
        if (key <= blocks[i].Value)
        {
            index = blocks[i].Index;
            break;
        }
    }

    //search key from block
    for (int i = index; i < index+blocks.Length-1; i++)
    {
        step++;
        if (ints[i] == key)
        {
            Console.WriteLine("BlockSearch setp:"+step);
            return key;
        }
    }
    return -1;
}

查找91的结果

image