快速排序基本思想:通过一趟排序将待排记录分成独立的两部分,其中一部分记录的关键字比另一部分记录的关键字要小,则可继续对这两部分记录进行排序,以达到整个序列有序的目的。。。
 
下面是一个快排的Demo:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 快速排序
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int[] arr={50,10,90,30,70,40,80,60,20};
            QuickSort(arr);
            for (int i = 0; i <arr.Length; i++)
            {
                Console.WriteLine(arr[i]);
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadKey();
        }

        private static void QuickSort(int[] arr)
        {
            QSort(arr,0,arr.Length-1);
        }

        private static void QSort(int[] arr, int low, int high)
        {
            int pivot;
            if (low < high)
            {
                //获得关键字(枢轴)
                pivot = Partition(arr,low,high);
                //将关键字左边的在调用QSort排序
                QSort(arr,low,pivot-1);
                //将右边的在排序
                QSort(arr,pivot+1,high);
            }
        }

        private static int Partition(int[] arr, int low, int high)
        {
            //将数组的第一个值作为关键字
            int pivotkey = arr[low];
            while (low < high)
            {
                //从后边开始比较,如果比关键字大,下标减一,在比较,如果小,交换
                while(low < high && arr[high] >= pivotkey)
               
                    high--;
                    swap(arr,low,high);
                //再从前边开始比较,若比关键字大,交换,否则,下标加一,循环比较,知道low==high
                while (low < high && arr[low] <= pivotkey)

                    low++;
                    swap(arr,low,high);
                                    
            }
            return low;
        }
         //两个数两两交换
        private static void swap(int[] arr, int low, int high)
        {
            int temp = arr[low];
            arr[low] = arr[high];
            arr[high] = temp;
        }
    }
}
posted on 2013-10-25 22:54  伊人撩月  阅读(192)  评论(0编辑  收藏  举报