码迷,mamicode.com
首页 > 编程语言 > 详细

一、快速排序

时间:2015-07-10 13:12:40      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:

快速排序

简介:

快速排序

是由C.A.R Hoare在1962年提出。

主要思想是:通过一趟排序将要排序的数据分割成独立的两个部分,其中一部分的所有数据都比另外一部分的的所有数据小,然后根据分治法的思想将这两个部分分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序数列。

 

具体代码参考《算法精解:C语言描述》

 

以下是我改用C#实现的程序:

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

namespace com.cnblogs.holt
{

    class QkSort
    {
        static Random ran = new Random();
        public static int partition(int[] array, int beg, int end)
        {
            int count=end-beg+1;
            int pval;
            int tmp;
            //three random value
            
            pval = array[beg+ran.Next(0,count-1)];
            beg--;
            end++;
            while (true)
            {
                //点一:do while
                do
                {
                    end--;
                } while (array[end] > pval);

                do
                {
                    beg++;
                } while (array[beg] < pval);

                if (beg >= end)
                {
                    break;
                }
                else
                {
                    tmp = array[beg];
                    array[beg] = array[end];
                    array[end] = tmp;
                }
            }
            //点二:返回end
            return end;
        }

        public static void qksort(int[] array,int beg,int end){
            int j;
            //点三:beg<end
            if (beg < end)
            {
                //点四:j而不是j-1
                j = partition(array, beg, end);
                qksort(array, beg, j);
                qksort(array,j+1,end);
            }
        }

        
        static void Main(string[] args)
        {
            int[] array = { 9, 8, 9, 6, 5, 4, 3, 2, 1, 0 };
            qksort(array, 0, 9);
            foreach (int i in array)
            {
                Console.WriteLine(i);
            }
        }
    }
}

本人菜鸟,如有错误请指出,谢谢。

 

一、快速排序

标签:

原文地址:http://www.cnblogs.com/holt/p/4635243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!