講述VB.NET QuickSort函數
VB.NET經過長時間的發展,很多用戶都很了解VB.NET QuickSort函數了,這里我發表一下個人理解,和大家討論討論。首先創建一個函數來在字符串數組中運行VB.NET QuickSort函數。我們將此函數放到應用程序類 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函數
這個函數需要三個參數:對數組的引用、下界和上界。它調用 Partition() 函數將數組分成兩部分,其中一部分包含 Pivot 值之前的所有字符串,另一部分包含 Pivot 值之后的所有字符串。然后,它調用自身來對每個部分進行排序。
上面修改中的注釋應該說明了每個代碼塊的作用。唯一的新概念就是 CompareTo() 方法的使用,該方法是 String 類的成員,并且應該是自說明的。
運行 QuickSort 應用程序
這一步完成 QuickSort C# 示例應用程序。現在,可以構建項目并運行應用程序。需要提供一個示例文本文件,以供其進行排序。將該文件放在與 EXE 文件相同的目錄中。
程序輸出
下面是已完成的 QuickSort C# .NET 示例應用程序的輸出。
【編輯推薦】