[ VB2010 ] - 氣泡排序法
氣泡排序法(Bubble Sort)
氣泡排序法的概念
氣泡排序法的過程
假設現在有個陣列資料,內容如下:
索引 0 1 2 3 4 5 6 7 8 9
數值 69 81 30 38 9 2 47 61 32 79
要如何將它遞增排列呢?
一開始,要將重點聚焦於陣列最尾端的位置,因為我們要先將整個陣列的最大值移動到陣列的最尾端。那麼,該如何從陣列中找到最大值並將其移動到最尾端呢?
從陣列最前方開始,逐次兩兩比較元素的大小,將兩個元素中較大的元素排在後面,即可逐漸將最大的元素從陣列前方擠到陣列後方。這就像是沉在水中的大氣泡,像要漂浮到水面上前,必須擠開其他的小氣泡一樣。
所以,若要擠出陣列的最大值至陣列的最尾端,位於陣列最前端的的69,要跟之後的元素(81)比大小,如下表:
●
索引 0 1 2 3 4 5 6 7 8 9
數值 69 81 30 38 9 2 47 61 32 79
└┬┘
69 < 81
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SortResult As String = ""
Dim Data(7) As Integer
Dim I, J, K As Integer, Buffer As Integer
Data(0) = Val(TextBox1.Text)
Data(1) = Val(TextBox2.Text)
Data(2) = Val(TextBox3.Text)
Data(3) = Val(TextBox4.Text)
Data(4) = Val(TextBox5.Text)
Data(5) = Val(TextBox6.Text)
Data(6) = Val(TextBox7.Text)
Data(7) = Val(TextBox8.Text)
For I = 0 To UBound(Data) - 1
For K = 0 To UBound(Data)
TextBox9.Text &= (I + 1).ToString & ". Data" & (K + 1).ToString & "=" & CStr(Data(K)) & "__"
Next
For J = 0 To UBound(Data) - 1
If Data(J) < Data(J + 1) Then
Buffer = Data(J)
Data(J) = Data(J + 1)
Data(J + 1) = Buffer
End If
Next
TextBox9.Text &= vbCrLf
Next
For I = 0 To UBound(Data)
SortResult &= CStr(Data(I)) & ","
Next
TextBox9.Text &= vbCrLf & "最後排序結果" & vbCrLf & (SortResult)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End
End Sub
End Class
沒有留言:
張貼留言