卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章20715本站已运行3410

如何使用C#编写基数排序算法

如何使用C#编写基数排序算法

如何使用C#编写基数排序算法

引言:
基数排序(Radix Sort)是一种非比较型的排序算法,适用于对整数进行排序。它的基本思想是将待排序的元素按照低位到高位的顺序依次进行排序,从而得到有序序列。相对于其他排序算法,基数排序的时间复杂度较低,并且具有稳定性。

实现步骤:

  1. 找出待排序数组中最大的数字,并确定其位数。
  2. 根据最大位数,从低位到高位,依次进行下一步操作。
  3. 对待排序数组进行计数排序,根据当前位的数字进行分组。
  4. 将分组后的数组重新组合成一个新的待排序数组。
  5. 重复步骤3和4,直到所有的位数都被比较完毕。

代码示例:
下面是使用C#编写的基数排序算法的示例代码:

using System;

public class RadixSort
{
    public static void Sort(int[] array)
    {
        int max = GetMaxValue(array);
        int digits = GetDigits(max);

        for (int i = 0; i < digits; i++)
        {
            CountingSort(array, i);
        }
    }

    private static int GetMaxValue(int[] array)
    {
        int max = array[0];
        for (int i = 1; i < array.Length; i++)
        {
            if (array[i] > max)
            {
                max = array[i];
            }
        }
        return max;
    }

    private static int GetDigits(int number)
    {
        int digits = 0;
        while (number > 0)
        {
            number /= 10;
            digits++;
        }
        return digits;
    }

    private static void CountingSort(int[] array, int digit)
    {
        int[] count = new int[10];
        int[] sortedArray = new int[array.Length];

        for (int i = 0; i < array.Length; i++)
        {
            int digitValue = GetDigitValue(array[i], digit);
            count[digitValue]++;
        }

        for (int i = 1; i < count.Length; i++)
        {
            count[i] += count[i - 1];
        }

        for (int i = array.Length - 1; i >= 0; i--)
        {
            int digitValue = GetDigitValue(array[i], digit);
            int index = count[digitValue] - 1;
            sortedArray[index] = array[i];
            count[digitValue]--;
        }

        for (int i = 0; i < array.Length; i++)
        {
            array[i] = sortedArray[i];
        }
    }

    private static int GetDigitValue(int number, int digit)
    {
        for (int i = 0; i < digit; i++)
        {
            number /= 10;
        }
        return number % 10;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        int[] array = { 170, 45, 75, 90, 802, 24, 2, 66 };
        
        Console.WriteLine("Before sorting:");
        foreach (int num in array)
        {
            Console.Write(num + " ");
        }
        
        RadixSort.Sort(array);
        
        Console.WriteLine("

After sorting:");
        foreach (int num in array)
        {
            Console.Write(num + " ");
        }
    }
}

运行结果:

Before sorting:
170 45 75 90 802 24 2 66 

After sorting:
2 24 45 66 75 90 170 802

总结:
基数排序算法是一种效率较高的排序算法,能够对整数数组进行快速排序。通过将待排序数组按照位数从低到高进行排序,最终得到有序的数组。使用C#编写基数排序算法时,我们需要首先找出待排序数组的最大值和位数,然后按照每一位进行计数排序,最后将排序后的数组重新组合得到有序结果。通过示例代码的运行结果可以看到,基数排序算法能够正确地对数组进行排序。

卓越飞翔博客
上一篇: 如何进行PHP秒杀系统的社交分享和微信登录集成
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏