0
点赞
收藏
分享

微信扫一扫

算法训练营Day56(动态规划16)

有点d伤 2024-01-28 阅读 12
c#算法

数据检索算法是指从数据集合(数组、表、哈希表等)中检索指定的数据项。

数据检索算法是所有算法的基础算法之一。

本文提供跳跃搜索的源代码。

1 文本格式

using System;

namespace Legalsoft.Truffer.Algorithm
{
    public static class ArraySearch_Algorithm
    {
        /// <summary>
        /// 跳跃搜索
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static int Jump_Search(int[] arr, int x)
        {
            int n = arr.Length;
            int step = (int)Math.Sqrt(n);
            int prev = 0;
            while (arr[Math.Min(step, n) - 1] < x)
            {
                prev = step;
                step += (int)Math.Sqrt(n);
                if (prev >= n)
                {
                    return -1;
                }
            }
            while (arr[prev] < x)
            {
                prev++;
                if (prev == Math.Min(step, n))
                {
                    return -1;
                }
            }
            if (arr[prev] == x)
            {
                return prev;
            }
            return -1;
        }
    }
}

代码不重要,思路最重要。

2 代码格式

using System;

namespace Legalsoft.Truffer.Algorithm
{
    public static class ArraySearch_Algorithm
    {
        /// <summary>
        /// 跳跃搜索
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static int Jump_Search(int[] arr, int x)
        {
            int n = arr.Length;
            int step = (int)Math.Sqrt(n);
            int prev = 0;
            while (arr[Math.Min(step, n) - 1] < x)
            {
                prev = step;
                step += (int)Math.Sqrt(n);
                if (prev >= n)
                {
                    return -1;
                }
            }
            while (arr[prev] < x)
            {
                prev++;
                if (prev == Math.Min(step, n))
                {
                    return -1;
                }
            }
            if (arr[prev] == x)
            {
                return prev;
            }
            return -1;
        }
    }
}
举报

相关推荐

0 条评论