快速排序(C#)实现

    在众多的排序算法中,快速排序由于有较好的性能(时间复杂度O(NlogN),优于常见的排序算法),且算法编码难度较小,常在工程实践和招聘中使用或考察。这里手撸并上传了一个快速排序算法的C#实现。主要参考了Wiki 百科的“快速排序”,以及严蔚敏老师《数据结构》一书对快速排序的讲解。源码如下:

static void Main(string[] args)
{
    int[] numbers = { 8, 3, 2, 4, 7, 6, 5 };

    // 输出未排序数组
    for (int i = 0; i < numbers.Length; i++)
    {
        Console.Write(numbers[i] + " ");
    }

    // 对该数组进行排序
    QuickSort(numbers, 0, numbers.Length - 1);

    // 输出已排序数组
    Console.Write("\n--------------------------\n");
    for (int i = 0; i < numbers.Length; i++)
    {
        Console.Write(numbers[i] + " ");
    }
}

static void QuickSort(int[] numbers, int start, int end)
{
    if (numbers == null || numbers.Length <= 0)
    {
        return;
    }

    if (start < 0 || end < 0 || start >= end)
    {
        return;
    }
    int pivort = start;
    int mid = Partition(numbers, start, end, pivort);// mid 已经定位
    QuickSort(numbers, start, mid - 1);
    QuickSort(numbers, mid + 1, end);
}

static int Partition(int[] numbers, int start, int end, int pivort)
{
    int pivortValue = numbers[pivort];

    // 置换在数组中位置
    Swap(numbers, end, pivort);

    int storeIndex = start;
    // 执行分割操作
    for (int i = start; i <= end - 1; i++)
    {
        if (numbers[i] < pivortValue)
        {
            Swap(numbers, i, storeIndex);
            storeIndex++;
        }
    }

    Swap(numbers, storeIndex, end);

    return storeIndex;
}

static void Swap(int[] array, int indexX, int indexY)
{
    int temp = array[indexX];
    array[indexX] = array[indexY];
    array[indexY] = temp;
}

 更多快速排序学习可参考 https://blog.csdn.net/wangxufa/article/details/121732098 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值