演算法實例-C#-快速排序-QuickSort

来源:http://www.cnblogs.com/aaron-clark-aic/archive/2016/04/01/5346619.html
-Advertisement-
Play Games

演算法實例 排序演算法Sort 快速排序QuickSort bing搜索結果 "http://www.bing.com/knows/search?q=%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95&mkt=zh cn&FORM=BKACAI" ...


演算法實例


##排序演算法Sort##
### 快速排序QuickSort ###
bing搜索結果
http://www.bing.com/knows/search?q=%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95&mkt=zh-cn&FORM=BKACAI

 *使用隊列*
 QuickSort排序中其實最貼近人類思考方式的實現是利用隊列技術
 1.建立左右隊列
 2.遍歷List,小於Pivot的放入左隊列,大於等於Pivot的放入右隊列
 3.左隊列出隊+Pivot+右隊列出隊  構造成一個第一次排序的List
 4.左隊列重覆步驟123,右隊列重覆123
 5.跳出迴圈的條件是隊列為空
 

 *使用指針對*
 1.將List尾部的元素設置為pivot
 2.設置一對指針,其中wallIndex指針標誌小於pivot的數,循環指針標誌遍歷的位置
 3.Note:關鍵演算法在於List中想要比較移動元素需要兩組指針,wallIndex用於定位需要插入的位置,循環指針用於遍歷元素.
 4.但是以文中演算法其實是QuickSort的變種模式,如圖我們如果以List最後的元素作為pivot的話,第一次排序結果因該是{49 38 13 27}49{65 97 76} 但是實際使用的排序演算法導致的結果應該為 {49 38 13 27}49{76 65 97}
 5.使用變種的演算法優勢在於使用的一對指針,實際減少了內存的使用和交換的開銷
 6.如果使用隊列技術,實際上額外使用了兩塊內存空間,但是其優勢在於可以更加的貼近人類的思維習慣

### 代碼展示 ###

#### 使用指針對 ####
https://github.com/aalhour/C-Sharp-Algorithms/blob/master/Algorithms/Sorting/QuickSorter.cs

 /// <summary>
 /// 
 /// </summary>
 public static class QuickSorter
 {
      
     /// <summary>
     /// The public APIs for the quick sort algorithm.
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="collection"></param>
     /// <param name="comparer"></param>
     public static void QuickSort<T>(this IList<T> collection, Comparer<T> comparer = null)
     {
         int startIndex = 0;
         int endIndex = collection.Count - 1;

         // If the comparer is Null, then initialize it using a default typed comparer
         comparer = comparer ?? Comparer<T>.Default;

         collection.InternalQuickSort(startIndex, endIndex, comparer);
     }

     /// <summary>
     /// The recursive quick sort algorithm
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="collection"></param>
     /// <param name="leftmostIndex"></param>
     /// <param name="rightmostIndex"></param>
     /// <param name="comparer"></param>
     private static void InternalQuickSort<T>(this IList<T> collection, int leftmostIndex, int rightmostIndex, Comparer<T> comparer)
     {
         // Recursive call check
         if (leftmostIndex < rightmostIndex)
         {
             int wallIndex = collection.InternalPartition(leftmostIndex, rightmostIndex, comparer);
             collection.InternalQuickSort(leftmostIndex, wallIndex - 1, comparer);
             collection.InternalQuickSort(wallIndex + 1, rightmostIndex, comparer);
         }
     }

     // The partition function, used in the quick sort algorithm
     /// <summary>
     ///  The partition function, used in the quick sort algorithm
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="collection"></param>
     /// <param name="leftmostIndex"></param>
     /// <param name="rightmostIndex"></param>
     /// <param name="comparer"></param>
     /// <returns></returns>
     private static int InternalPartition<T>(this IList<T> collection, int leftmostIndex, int rightmostIndex, Comparer<T> comparer)
     {
         int wallIndex, pivotIndex;
         
         // Choose the pivot
         pivotIndex = rightmostIndex;
         T pivotValue = collection[pivotIndex];

         // Compare remaining array elements against pivotValue
         wallIndex = leftmostIndex;

         // Loop until pivot: exclusive!
         for (int i = leftmostIndex; i <= (rightmostIndex - 1); i++)
         {
             // check if collection[i] <= pivotValue
             if (comparer.Compare(collection[i], pivotValue) <= 0)
             {
                 collection.Swap(i, wallIndex);
                 wallIndex++;
             }
         }

         collection.Swap(wallIndex, pivotIndex);

         return wallIndex;
     }

 }

#### 使用隊列 ####

 /// <summary>
 /// using Queue for quick sort
 /// </summary>
 public static class QuickSorterA
 {
     public static void QuickSortA<T>(this IList<T> collection, Comparer<T> comparer = null)
     {
         // If the comparer is Null, then initialize it using a default typed comparer
         comparer = comparer ?? Comparer<T>.Default;
         Queue<T> _queue = new Queue<T>(collection);
         _queue.InternalQuickSortA(comparer);
         collection.Clear();
         foreach (var item in _queue)
         {
             collection.Add(item);
         }

     }

     private static void InternalQuickSortA<T>(this Queue<T> collection, Comparer<T> comparer)
     {
         if (collection.Count <=0)
         {
             return;
         }
         // Recursive call check
         Queue<T> _leftQueue = new Queue<T>();
         Queue<T> _rightQueue = new Queue<T>();
         T _povit = collection.Dequeue();
         foreach (var item in collection)
         {
             if (comparer.Compare(item, _povit) <= 0)
             {
                 _leftQueue.Enqueue(item);
             }
             else
             {
                 _rightQueue.Enqueue(item);
             }
         }

         _leftQueue.InternalQuickSortA<T>(comparer);
         _rightQueue.InternalQuickSortA<T>(comparer);

         collection.Clear();
         foreach (var item in _leftQueue)
         {
             collection.Enqueue(item);
         }

         collection.Enqueue(_povit);

         foreach (var item in _rightQueue)
         {
             collection.Enqueue(item);
         }
     }
 }

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 來自系統媽:http://www.xitongma.com 深度技術GHOST win7系統32,64位經典優化版 V2016年3月 系統概述 深度技術ghost win7系統64位經典優化版適用於筆記本、品牌機,也支持組裝相容機,安裝後自動激活,可供品牌機專賣店及普通用戶安裝使用。保留了在區域網辦 ...
  • 介面的出現,是為瞭解決C#中不允許多重繼承的問題。 1、什麼是介面? 我覺得可以把介面理解為對一組方法聲明進行的統一命名,但這些方法沒有提供任何實現。 通過介面,就可以對方法進行統一管理,避免了在每種類型中重覆定義這些方法。 2、如何使用介面來編程 2.1 介面的定義 interface ICust ...
  • 說明 最近在網上下載了一些資料,所有的文件名被加上網站相關信息,導致文件名非常長.再者,我也不喜歡這樣的做法.那麼,就要重新修改文件名,文件還不少,手動修改確實不便.於是就自己寫了個小工具,基本滿足需要了. 下載 "github" "百度雲" 功能 批量替換文件名中內容 按序號批量重命名 源碼 代碼 ...
  • 一. 使用意圖 常常在開發過程中,碰到一個實體上的屬性值,要賦值給另外一個相類似實體屬性時,且屬性有很多的情況。一般不利用工具的話,就要實例化被賦值實體B,然後再將實體A的欄位一個個賦值給B的屬性,單單寫這些沒有技術含量的賦值語句,就要用很大的代碼篇幅。假如做得好一點的話,一般就是利用反射的方式,將 ...
  • 分類:Unity、C#、VS2015 創建日期:2016-04-02 一、簡介 預製體(Prefab,也叫預設)是“存儲在工程視圖(Project View)中”的一種特殊的資源,是一種可重覆使用的游戲對象(GameObject)的容器。 如果在Project中有多個預製體(Prefab),為了容易... ...
  • 下拉框的兩級聯動是我們開發中經常遇到一種情況。比如一個學生管理系統中,根據年級、科目及姓名查詢學生考試成績,年級和科目都是硬碟中的有限數據(資料庫)而學生則可以有用戶手動指定,這時在資料庫中有年級和科目兩張表,每門科目都對應一個年級,所以我們可以用兩個下拉框(Combobox)來存儲年級和科目信息來... ...
  • 分類:Unity、C#、VS2015 創建日期:2016-04-02 一、簡介 利用Unity內置的基本模型和工具,不需要藉助任何其他的三維建模軟體,就可以直接創建出各種3D模型,這是這一章我們首先學習的內容。 當你學會了基本操作技巧後,再進一步利用(3ds Max、Maya、Blender等)專業 ...
  • 本文略微有些長,花了好幾晚時間編輯修改,若在措辭排版上有問題,請諒解。本文共分為四篇,下麵是主要內容,也是軟體開發基本流程。 階段 描述 需求分析 主要描述實現本程式的目的及對需求進行分析,即為什麼要花時間來編寫,需要哪些功能等; 方案設計 根據現有的需求,設計出一個可行的方案(即使可能還存在某些問 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...