无序数组在排序后的最大相邻查

前言

原理后续补齐

代码

public class Bucket
{
    public int? max { get; set; }

    public int? min { get; set; }
}
class Program
{

    public static int getMaxSortedDistance(int[] array)
    {
        int max = array[0];
        int min = array[0];
        for (int i = 1; i < array.Length-1; i++)
        {
            if (array[i] > max)
            {
                max = array[i];
            }

            if (array[i] < min)
            {
                min = array[i];
            }
        }

        var BucketNumber = array.Length;
        double BucketAreaNumber =((double)(max - min)) / (BucketNumber-1);
        Bucket[] buckets = new Bucket[BucketNumber];
        for (int i = 0; i < buckets.Length; i++)
        {
            buckets[i] = new Bucket();
        }
        for (int i = 0; i < array.Length; i++)
        {
            int index=Convert.ToInt32((array[i] - min) / BucketAreaNumber);
            var currentBucket=buckets[index];
           
            if (currentBucket.max == null || currentBucket.max < array[i])
            {
                currentBucket.max = array[i];
            }
            

            if (currentBucket.min==null||currentBucket.min > array[i])
            {
                currentBucket.min = array[i];
            }
        }
        var MaxsortedDistance = 0;

        for (int i=0;i< buckets.Length-1;i++)
        {
            if (buckets[i].max != null)
            {
                var constindex = i;
                while(buckets[i + 1].min == null)
                {
                    i++;
                }
                if ((buckets[i + 1].min - buckets[constindex].max) > MaxsortedDistance)
                {
                    MaxsortedDistance = (int)(buckets[i + 1].min - buckets[constindex].max);
                }
            }
        }
        return MaxsortedDistance;
    }

    static void Main(string[] args)
    {
        int[] array = new int[] {2,9,5,10,6,50,21,31 };
        Console.WriteLine(getMaxSortedDistance(array));
        Console.ReadKey();
    }
}
上一篇:matlab练习程序(油画效果)


下一篇:20191209-八大排序之基数排序