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;
            }
        }
    }
  • 相关阅读:
    HDU 3579 Hello Kiki 中国剩余定理
    DHU 1788 Chinese remainder theorem again 中国剩余定理
    初学--求解模线性方程组(中国余数定理)。
    山东第四届省赛: Boring Counting 线段树
    山东第四届省赛C题: A^X mod P
    福州大学oj 1752 A^B mod C ===>数论的基本功。位运用。五星*****
    HDU 1576 A/B 暴力也能过。扩展欧几里得
    POJ 1061 青蛙的约会 扩展欧几里德--解不定方程
    HDU 2669 Romantic 扩展欧几里德---->解不定方程
    南阳nyoj 56 阶乘因式分解(一)
  • 原文地址:https://www.cnblogs.com/zcz527/p/3388721.html
Copyright © 2011-2022 走看看