快速排序算法

本文深入探讨了快速排序算法的核心机制及其在处理随机数据集时的优化策略。通过详细分析算法流程,包括递归划分、基准元素选择及交换操作,文章阐述了如何提高算法效率。特别地,介绍了选择中间值作为基准的技巧,并提供了一个实际应用示例。此教程旨在为读者提供一种快速、高效的排序方法,适用于大量无序数据的场景。

快速排序算法是最快的排序算法,当然它是针对大量通常无序的集合而言是正确的。

public void QSort()

{

    RecQSort(0, numElements - 1);

}

public void RecQSort(int first, int last)

{

    if ((last - first) <= 0)

        return;

    else

    {

        int part = this.Partition(first, last);

        RecQSort(first, part - 1);

        RecQSort(part + 1, last);

    }

}

public int Partition(int first, int last)

{

    int pivotVal = arr[first];

    int theFirst = first;

    bool okSide;

    first++;

    do

    {

        okSide = true;

        while (okSide)

            if (arr[first] > pivotVal)

                okSide = false;

            else

            {

                first++;

                okSide = (first <= last);

            }

        okSide = true;

        while (okSide)

            if (arr[last] <= pivotVal)

                okSide = false;

            else

            {

                last--;

                okSide = (first <= last);

            }

        if (first < last)

        {

            Swap(first, last);

            this.DisplayElements();

            first++;

            last--;

        }

    } while (first <= last);

    Swap(theFirst, last);

    this.DisplayElements();

    return last;

}

public void Swap(int item1, int item2)

{

    int temp = arr[item1];

    arr[item1] = arr[item2];

    arr[item2] = temp;

}

如果数组内的的数据是随机的,那么选择第一个

最流行的选择中间值得方法。

theFirst = arr[(int)arr.GetUpperBound(0) / 2]

转载于:https://www.cnblogs.com/chaobao/archive/2012/02/11/2347031.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值