| 作者:未知 文章来源:microsoft 点击数: 33056 更新时间:2004-9-27 | |
步骤 7. 创建函数最后一步就是创建一个函数来在字符串数组中运行 QuickSort。我们将此函数放到应用程序类 QuickSortApp 之中。 修改源代码更改 Visual Basic 源文件 (module1.vb),如下面以斜体突出显示的 代码所示。其他的差异(如类名)可忽略不计。 ' Import namespaces
Imports System
Imports System.Collections
Imports System.IO
Module Module1
Sub Main()
... ... ...
' Pass to QuickSort function
QuickSort(szContents, 0, szContents.Count - 1)
... ... ...
End Sub
' QuickSort implementation
Sub QuickSort(ByRef szArray As ArrayList, ByVal nLower As Integer, _
ByVal nUpper As Integer)
' Check for non-base case
If nLower < nUpper Then
' Split and sort partitions
Dim nSplit As Integer
nSplit = Partition(szArray, nLower, nUpper)
QuickSort(szArray, nLower, nSplit - 1)
QuickSort(szArray, nSplit + 1, nUpper)
End If
End Sub
' QuickSort partition implementation
Function Partition(ByRef szArray As ArrayList, _
ByVal nLower As Integer, ByVal nUpper As Integer) As Integer
' Pivot with first element
Dim szPivot As String
Dim nLeft, nRight As Integer
nLeft = nLower + 1
szPivot = szArray(nLower)
nRight = nUpper
' Partition array elements
Dim szSwap As String
While nLeft <= nRight
' Find item out of place
While nLeft <= nRight
If szArray(nLeft).CompareTo(szPivot) > 0 Then Exit While
nLeft = nLeft + 1
End While
While nLeft <= nRight
If szArray(nRight).CompareTo(szPivot) <= 0 Then Exit While
nRight = nRight – 1
End While
' Swap values if necessary
If (nLeft < nRight) Then
szSwap = szArray(nLeft)
szArray(nLeft) = szArray(nRight)
szArray(nRight) = szSwap
nLeft = nLeft + 1
nRight = nRight – 1
End If
End While
' Move pivot element
szSwap = szArray(nLower)
szArray(nLower) = szArray(nRight)
szArray(nRight) = szSwap
Return nRight
End Function
End Module
QuickSort() 函数这个函数需要三个参数:对数组的引用、下界和上界。它调用 Partition() 函数来将数组分成两部分,其中一部分包含 Pivot 值之前的所有字符串,另一部分包含 Pivot 值之后的所有字符串。然后,它调用自身来对每个部分进行排序。 上面修改中的注释应该说明了每个代码块的作用。唯一的新概念就是 CompareTo() 方法的使用,该方法是 String 类的成员,并且应该是自说明的。 运行 QuickSort 应用程序这一步完成 QuickSort Visual Basic .NET 示例应用程序。现在,可以构建项目并运行应用程序。需要提供一个示例文本文件,以供其进行排序。将该文件放在与 EXE 文件相同的目录中。 ![]() 程序输出下面是已完成的 QuickSort Visual Basic .NET 示例应用程序的输出。您可以查看示例输入文件 'example.txt' 和输出文件 'output.txt'。 ![]() |
正文
VB.NET 入门教程52005-09-24 07:29:00
【评论】 【打印】 【字体:大 中 小】 本文链接:http://blog.pfan.cn/iamben250/5194.html
阅读(1711) | 评论(0)
版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!



评论