講述VB.NET QuickSort函數(shù)
VB.NET經(jīng)過長時間的發(fā)展,很多用戶都很了解VB.NET QuickSort函數(shù)了,這里我發(fā)表一下個人理解,和大家討論討論。首先創(chuàng)建一個函數(shù)來在字符串?dāng)?shù)組中運行VB.NET QuickSort函數(shù)。我們將此函數(shù)放到應(yīng)用程序類 QuickSortApp 之中。
修改源代碼
更改 C# 源文件 (class1.cs),如下面以斜體突出顯示的 代碼所示。其他的差異(如類名)可忽略不計。
- // Import namespaces
 - using System;
 - using System.Collections;
 - using System.IO;
 - // Declare namespace
 - namespace MsdnAA
 - {
 - // Declare application class
 - class QuickSortApp
 - {
 - // Application initialization
 - static void Main (string[] szArgs)
 - {
 - ... ... ...
 - // Pass to QuickSort function
 - QuickSort (szContents, 0, szContents.Count - 1);
 - ... ... ...
 - }
 - // QuickSort implementation
 - static void QuickSort (ArrayList szArray, int nLower, int nUpper)
 - {
 - // Check for non-base case
 - if (nLower < nUpper)
 - {
 - // Split and sort partitions
 - int nSplit = Partition (szArray, nLower, nUpper);
 - QuickSort (szArray, nLower, nSplit - 1);
 - QuickSort (szArray, nSplit + 1, nUpper);
 - }
 - }
 - // QuickSort partition implementation
 - static int Partition (ArrayList szArray, int nLower, int nUpper)
 - {
 - // Pivot with first element
 - int nLeft = nLower + 1;
 - string szPivot = (string) szArray[nLower];
 - int nRight = nUpper;
 - // Partition array elements
 - string szSwap;
 - while (nLeft <= nRight)
 - {
 - // Find item out of place
 - while (nLeft <= nRight)
 - {
 - if (((string) szArray[nLeft]).CompareTo (szPivot) > 0)
 - break;
 - nLeftnLeft = nLeft + 1;
 - }
 - while (nLeft <= nRight)
 - {
 - if (((string) szArray[nRight]).CompareTo (szPivot) <= 0)
 - break;
 - nRightnRight = nRight - 1;
 - }
 - // Swap values if necessary
 - if (nLeft < nRight)
 - {
 - szSwap = (string) szArray[nLeft];
 - szArray[nLeft] = szArray[nRight];
 - szArray[nRight] = szSwap;
 - nLeftnLeft = nLeft + 1;
 - nRightnRight = nRight - 1;
 - }
 - }
 - // Move pivot element
 - szSwap = (string) szArray[nLower];
 - szArray[nLower] = szArray[nRight];
 - szArray[nRight] = szSwap;
 - return nRight;
 - }
 - }
 - }
 
VB.NET QuickSort函數(shù)
這個函數(shù)需要三個參數(shù):對數(shù)組的引用、下界和上界。它調(diào)用 Partition() 函數(shù)將數(shù)組分成兩部分,其中一部分包含 Pivot 值之前的所有字符串,另一部分包含 Pivot 值之后的所有字符串。然后,它調(diào)用自身來對每個部分進行排序。
上面修改中的注釋應(yīng)該說明了每個代碼塊的作用。唯一的新概念就是 CompareTo() 方法的使用,該方法是 String 類的成員,并且應(yīng)該是自說明的。
運行 QuickSort 應(yīng)用程序
這一步完成 QuickSort C# 示例應(yīng)用程序。現(xiàn)在,可以構(gòu)建項目并運行應(yīng)用程序。需要提供一個示例文本文件,以供其進行排序。將該文件放在與 EXE 文件相同的目錄中。

程序輸出
下面是已完成的 QuickSort C# .NET 示例應(yīng)用程序的輸出。

【編輯推薦】















 
 
 
 
 
 
 