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;
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
VB.NET QuickSort函数
这个函数需要三个参数:对数组的引用、下界和上界。它调用 Partition() 函数将数组分成两部分,其中一部分包含 Pivot 值之前的所有字符串,另一部分包含 Pivot 值之后的所有字符串。然后,它调用自身来对每个部分进行排序。
上面修改中的注释应该说明了每个代码块的作用。唯一的新概念就是 CompareTo() 方法的使用,该方法是 String 类的成员,并且应该是自说明的。
运行 QuickSort 应用程序
这一步完成 QuickSort C# 示例应用程序。现在,可以构建项目并运行应用程序。需要提供一个示例文本文件,以供其进行排序。将该文件放在与 EXE 文件相同的目录中。
程序输出
下面是已完成的 QuickSort C# .NET 示例应用程序的输出。
【编辑推荐】