• 快速排序


    快速排序基本思想:通过一趟排序将待排记录分成独立的两部分,其中一部分记录的关键字比另一部分记录的关键字要小,则可继续对这两部分记录进行排序,以达到整个序列有序的目的。。。
     
    下面是一个快排的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;
            }
        }
    }
  • 相关阅读:
    内置函数(十)
    常用命令
    函数式编程(九)——map,filter,reduce
    函数(八)-函数和匿名函数
    设计模式(十三)——观察者模式
    Confluence 6 重要缓存和监控
    Confluence 6 数据中心的缓存
    Confluence 6 配置文件和key
    Confluence 6 缓存性能示例
    Confluence 6 缓存性能优化
  • 原文地址:https://www.cnblogs.com/zcz527/p/3388721.html
Copyright © 2020-2023  润新知