zoukankan      html  css  js  c++  java
  • 快速排序

    快速排序基本思想:通过一趟排序将待排记录分成独立的两部分,其中一部分记录的关键字比另一部分记录的关键字要小,则可继续对这两部分记录进行排序,以达到整个序列有序的目的。。。
     
    下面是一个快排的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;
            }
        }
    }
  • 相关阅读:
    2008俱乐部高校行之中南民族大学
    [更新]MSDN中Webcast "WPF中的图形系统系列" 课程预告及反馈
    7月20日 武汉.NET俱乐部在线沙龙!
    2007武汉.NET俱乐部沙龙VS2008、WPF、Silverlight
    MSDN新年第一次WebCast总结
    [评]Microsoft Visual Web Developer 2008 Step by Step, Express Edition
    [老爸创作的歌词]我从瓦砾中站起
    [Expert MS IL Assembler]武汉.NET俱乐部在线沙龙与线下聚会
    2008开年大礼:《Application = Code + Markup》中文版面世
    2009武汉.NET俱乐部活动之黄冈站
  • 原文地址:https://www.cnblogs.com/zcz527/p/3388721.html
Copyright © 2011-2022 走看看