• 二分查找(折半查找)


    非递归写法:

                public static int search(int left, int right, int[] array, int key)
                {
    
                    int mid = (left + right) / 2;
                    //不在当前搜索集里面
                    if (key < array[0] || key > array[array.Length - 1])
                    {
                        return -1;
                    }
                    while (left <= right)
                    {
    
                        if (array[mid] == key)
                        {
                            return mid;
                        }
                        else if (array[mid] > key)
                        {
                            right = mid - 1;
                        }
                        else
                        {
                            left = mid + 1;
                        }
                    }
                    return -1;
                }

    递归写法:

       public static int search(int left, int right, int[] array, int key)
                {
                    int mid = (left + right) / 2;
                    //不在当前搜索集里面
                    if (key < array[0] || key > array[array.Length - 1])
                    {
                        return -1;
                    }
                    while (left <= right)
                    {
    
                        if (array[mid] == key)
                        {
                            return mid;
                        }
                        else if (array[mid] > key)
                        {
                            return search(left,mid-1,array,key);
                        }
                        else
                        {
                            return search(mid+1,right,array,key);
                        }
                    }
                    return -1;
                }

    Main函数:

     public static void Main()
                {
                    int[] array = { 10, 14, 16, 18, 25, 30, 45, 65, 76, 81, 90, 102, 156 };
                    foreach(int a in array)
                    {
                        Console.Write(a+" ");
    
                    }
                    Console.WriteLine();
                    Console.WriteLine("查找10000:"+search(1,array.Length,array,10000));
                    Console.WriteLine("查找5:" + search(1,array.Length,array, 5));
                    Console.WriteLine("查找18:" + search(1, array.Length , array, 18));
                    Console.ReadKey();
                }
  • 相关阅读:
    Python3---常见函数---super()
    Python3---常见函数---type()
    Python3---面对对象
    Python3---BeautifulSoup---节点选择器
    Python3---Beautiful Soup
    0X01应用程序黑客技术
    Python3---标准库---re
    (trie) UVA
    (trie)UVALive
    (平方分割)POJ 2104 K-th Number
  • 原文地址:https://www.cnblogs.com/tiancaige/p/13432887.html
Copyright © 2020-2023  润新知