Quick sort 及其随机化版本

Quick sort是一种排序算法,对n个数进行排序,最坏的情况是n的2次方。虽然这个是最坏运行时间比较差,但快速排序通常是用于排序的最佳的实用选择,这是因为quick sort平均性能相当好,期望的运行时间为nlgn。另外,quick sort 能够进行就地排序,在虚拟的坏境中也能很好的工作。

像合并排序一样,quick sort 也是基于分治模式的。用c#语言实现的quick sort 代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ArithmeticLibrary

{

     public class QuickSortArithmetic

    {

         public QuickSortArithmetic()

         { }

         public void QuickSort(Int32[] a, Int32 begin, Int32 end)

         {

             Int32 q = -1;

             if (begin < end)

             {

                 q = Partition(a,begin,end);

                 QuickSort(a, begin, q - 1);

                 QuickSort(a, q + 1, end);

             }

         }

 

         private int Partition(int[] a, int begin, int end)

         {

             Int32 x = a[end];

             Int32 i = begin - 1;

             for (Int32 j = begin; j <= end - 1; j++)

             {

                 if (a[j] <= x)

                 {

                     i++;

                     Int32 temp = a[j];

                     a[j] = a[i];

                     a[i] = temp;

                 }

             }

             Int32 t = a[i + 1];

             a[i + 1] = a[end];

             a[end] = t;

             return i + 1;

         }

    }

}

具体的调用如下:

Int32[] a = new Int32[12] { 13,19,9,5,12,8,7,4,21,2,6,11};

            Console.WriteLine("Begin Sort:");

            foreach (Int32 item in a)

            {

                Console.Write(item.ToString()+" ");

            }

            QuickSortArithmetic quickSort = new QuickSortArithmetic();

            quickSort.QuickSort(a, 0, a.Length-1);

            Console.WriteLine("After Sort:");

            foreach (Int32 item in a)

            {

                Console.Write(item.ToString() + " ");

            }

从上面介绍quick sort排序可以看出,其实对数组a中间的子数组进行排序。例如,对a[5,10]之间的元素进行quick sort

下面介绍快速排序的随机化的版本

quick sort排序的随机化版本中,我们不是实用采用a[end]作为主元,而是从子数组a[begin,end]中随机的选择一个元素,既将a[end]a[begin,end]中随机选出的一个元素交换。

PartitionQuickSort 所作的改动比较小。增加了一个RandomizedPartition的方法,具体的c#代码如下:

private Int32 RandomizedPartition(Int32[] a, Int32 begin, Int32 end)

         {

             Random rand=new Random();

             Int32 i = rand.Next(begin, end + 1);

             Int32 temp = a[end];

             a[end] = a[i];

             a[i] = temp;

             return Partition(a, begin, end);

         }

QuickSort方法如下:

public void QuickSort(Int32[] a, Int32 begin, Int32 end)

         {

             Int32 q = -1;

             if (begin < end)

             {

                 q = RandomizedPartition(a, begin, end);

                 QuickSort(a, begin, q - 1);

                 QuickSort(a, q + 1, end);

             }

         }

Partition方法还是先前的那个不变。

posted @ 2010-10-23 18:57  chenping2008  阅读(432)  评论(0编辑  收藏  举报