此程序假设按姓氏(aryTemp和aryTemp2中的索引1)按升序对记录(在arySort中)进行排序,并将结果放在旧的预加载未分类记录的列表框中。
它奇怪地排序它们,我必须多次单击Ascending按钮以获得我想从点击按钮获得的实际排序结果。
为什么不用单击鼠标对项目进行排序?
来源:
Public Class Form1
Dim FILE_NAME As String = "Students.txt"
Dim numberOfRecords As Integer 'total number of records
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
lstBox.Items.Add(objReader.ReadLine)
numberOfRecords += 1
Loop
objReader.Close()
End If
End Sub
Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
'load all students into array
Dim arySort(numberOfRecords - 1) As String
Dim aryTemp() As String 'holds first record's last name
Dim aryTemp2() As String 'holds second record's last name
For i = 0 To numberOfRecords - 1
arySort(i) = lstBox.Items(i)
Next
Dim temp As String 'holds temporary record
Dim k As Integer
For i = 0 To arySort.Length - 2
aryTemp = Split(arySort(i), " ")
For k = i + 1 To arySort.Length - 1
aryTemp2 = Split(arySort(k), " ")
If aryTemp(1) < aryTemp2(1) Then
temp = arySort(k)
arySort(k) = arySort(i)
arySort(i) = temp
End If
Next
Next
lstBox.Items.Clear()
numberOfRecords = 0
For i = 0 To arySort.Length - 1
lstBox.Items.Add(arySort(i))
numberOfRecords += 1
Next
End Sub
End Class
答案 0 :(得分:1)
如果您只需要对列表进行排序(正如您在评论中所说的那样),不实现您自己的排序机制,而是使用.NET:
' Define how we want to compare items '
Function compareByLastName(ByVal item1 As String, ByVal item2 As String) As Integer
Return String.Compare(item1.Split(" ")(1), item2.Split(" ")(1))
End Function
Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
' load all students into array '
Dim arySort(numberOfRecords - 1) As String
For i = 0 To numberOfRecords - 1
arySort(i) = lstBox.Items(i)
Next
' Use built-in .NET magic '
Array.Sort(arySort, AddressOf compareByLastName)
' Write the values back into your list box '
lstBox.Items.Clear()
numberOfRecords = 0
For i = 0 To arySort.Length - 1
lstBox.Items.Add(arySort(i))
numberOfRecords += 1
Next
End Sub
这使用.NET类库的内置快速排序算法。以下是我们使用的方法的文档:Array.Sort(T(), Comparison(Of T))。
答案 1 :(得分:0)
与我的工作冒泡分类比较:
Public Sub BubbleSort(ByVal arr() As Integer)
Dim flag As Boolean = False
For i As Integer = 0 To arr.Length - 1
For j As Integer = 0 To arr.Length - 2 - i
If arr(j + 1) < arr(j) Then
flag = True
Dim temp As Integer = arr(j)
arr(j) = arr(j + 1)
arr(j + 1) = temp
End If
Next
If flag = False Then Return ' no swaps =>already sorted
Next
End Sub
答案 2 :(得分:0)
我发现您的算法存在两个主要问题:
这不是冒泡排序。 Bubble sort交换相邻的元素,即它与i + 1交换i。另一方面,你用第一个j&gt;交换一些元素i。我姓名(i)&lt;名字(J)。也许您应该以伪代码向我们展示您实际尝试实施的算法?
aryTemp
包含元素i,aryTemp2
包含一些元素j&gt;一世。如果aryTemp(1) < aryTemp2(1)
,为什么要交换元素?如果您希望元素按升序排序,那么这不是正确的顺序吗?