講述VB.NET QuickSort函數(shù)
VB.NET經(jīng)過長(zhǎng)時(shí)間的發(fā)展,很多用戶都很了解VB.NET QuickSort函數(shù)了,這里我發(fā)表一下個(gè)人理解,和大家討論討論。首先創(chuàng)建一個(gè)函數(shù)來在字符串?dāng)?shù)組中運(yùn)行VB.NET QuickSort函數(shù)。我們將此函數(shù)放到應(yīng)用程序類 QuickSortApp 之中。
修改源代碼
更改 C# 源文件 (class1.cs),如下面以斜體突出顯示的 代碼所示。其他的差異(如類名)可忽略不計(jì)。
- // 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ù)
這個(gè)函數(shù)需要三個(gè)參數(shù):對(duì)數(shù)組的引用、下界和上界。它調(diào)用 Partition() 函數(shù)將數(shù)組分成兩部分,其中一部分包含 Pivot 值之前的所有字符串,另一部分包含 Pivot 值之后的所有字符串。然后,它調(diào)用自身來對(duì)每個(gè)部分進(jìn)行排序。
上面修改中的注釋應(yīng)該說明了每個(gè)代碼塊的作用。唯一的新概念就是 CompareTo() 方法的使用,該方法是 String 類的成員,并且應(yīng)該是自說明的。
運(yùn)行 QuickSort 應(yīng)用程序
這一步完成 QuickSort C# 示例應(yīng)用程序?,F(xiàn)在,可以構(gòu)建項(xiàng)目并運(yùn)行應(yīng)用程序。需要提供一個(gè)示例文本文件,以供其進(jìn)行排序。將該文件放在與 EXE 文件相同的目錄中。
程序輸出
下面是已完成的 QuickSort C# .NET 示例應(yīng)用程序的輸出。
【編輯推薦】