奇偶排序,或奇偶換位排序,或磚排序,是一種相對簡單的排序演算法,最初發明用於有在地互連的並行計算。這是與冒泡排序特點類似的一種比較排序。該演算法中,透過比較數組中相鄰的(奇-偶)位置數字對,如果該奇偶對是錯誤的順序(第一個大於第二個),則交換。下一步重覆該操作,但針對所有的(偶-奇)位置數字對。如此交替進行下去。
奇偶排序法(Odd and Even Sort)是使用相鄰兩個資料相互比較後易位(如a[0]與a[1]比較,a[2]與a[3]比較…..)
易位後相鄰兩個資料再相互比較(如a[1]與a[2]比較,a[3]與a[4]比較…..)
接著還原到原先位置相互比較,再易位資料比較…,如此下去,直到完成為止。
第一次排列將數列以兩個數為一組,分成四組做比較,結果將小數置於前面,大數置於後面:
第二次排列以易位相鄰兩個資料相互比較:
將每一排列的步驟,列出其排列順序:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OK As Boolean = False
Dim SortResult As String = ""
Dim Data(7), M As Integer
Dim I, J, K As Integer, Buffer As Integer
M = 1
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)
Do Until OK = True
OK = True
For I = 0 To 1
For K = 0 To UBound(Data)
TextBox9.Text &= (M).ToString & ". Data" & (K + 1).ToString & "=" & CStr(Data(K)) & "__"
Next
For J = I To UBound(Data) - 1 Step 2
If Data(J) < Data(J + 1) Then
Buffer = Data(J)
Data(J) = Data(J + 1)
Data(J + 1) = Buffer
OK = False
End If
Next
M += 1
TextBox9.Text &= vbCrLf
Next
Loop
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
沒有留言:
張貼留言