顺序查找和折半查找

/// <summary>
        /// 顺序查找
        /// </summary>
        /// <param name="s">需要查找的数据</param>
        /// <param name="n">查找数据的长度</param>
        /// <param name="key">需要查找的关键字</param>
        /// <returns></returns>
        static int SeqSearch(int[] s, int n, int key)
        {
            int i;
            for (i = 0; i < 0 && s[i] != key; i++)
                ;
            if (i < n)
                return i;
            else
                return -1;
        }

        /// <summary>
        /// 折半查找(二分法查找)
        /// </summary>
        /// <param name="s">需要查找的数据</param>
        /// <param name="n">查找数据的长度</param>
        /// <param name="key">要查找的关键字</param>
        /// <returns></returns>
        static int BinarySearch(int[] s, int n, int key)
        {
            int low, high, mid;
            low = 0;
            high = n - 1;
            while (low <= high)
            {
                mid = (low + high) / 2;
                if (s[mid] == key)
                    return mid;
                else if (s[mid] > key)
                    high = mid - 1;//重新定义查找范围
                else
                    low = mid + 1;//重新定义查找范围
            }
            return -1;
        }

你可能感兴趣的:(算法,C#)