吃螺丝

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

合并排序完成,现在来个快速排序

简单说下快速排序

快速排序是将一个集合,设一个中间元素,然后将集合分成3个集合

左边集合的子集小于等于中间元素 ---- 中间元素 ---- 右边子集大于等于中间元素

 

其可采用递归调用的方法解决,

下面是简单的快速排序,还有很多变异版本,请查阅相关资料, 一下是原代码

//////////////////////////////////////////////////////////////分割线///////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FastSort
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arrayTest = new int[] { 3,4,7,8,1,6,10,0,5};
            QuickSort(arrayTest,0,8);   //递归调用
            foreach (int test in arrayTest)
            {
                Console.Write(test.ToString()+" ");
            }
            Console.Read();
        }


        static int Partition(int[] test,int p,int r)  //分离  核心算法  双向扫描
        {
            int i = p;
            int j = r + 1;

            int x = test[p];

            while (true)
            {
                while (test[--j] > x)
                {
                   
                }
                while (test[++i] < x)
                {
                   
                }
                if (i<j)
                {
                    Swap(test,i,j); 
                }
                else
                {
                    Swap(test, p, j);
                    return j;
                }
            }
        }

        static void QuickSort(int[] test,int l,int r)
        {
            if (l>=r)//如果左右相等  跳出
            {
                return;
            }
            int m = Partition(test, l, r);
            QuickSort(test,l,m);
            QuickSort(test,m+1,r);

           
        }

        static void Swap(int[] test,int x,int y)
        {
            if (x==y)
            {
                return;
            }
            int temp = test[x];
            test[x] = test[y];
            test[y] = temp;
        }
    }
}
s

posted on 2011-09-29 01:16  吃螺丝  阅读(369)  评论(0编辑  收藏  举报