This is a VB.NET implementation of a bubble sort. The array has been declared with form level scope and initialised in the form’s load event handler.
An enhanced version of the program is also shown. In this version a Boolean flag is tested to see if there has been a swap during each pass. If there have been no swaps, it is assumed that the data is now in order and there is no need for any more passes.
Public Class Form1 Dim aData(9) As Integer Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load aData(0) = 6 aData(1) = 5 aData(2) = 9 aData(3) = 10 aData(4) = 8 aData(5) = 7 aData(6) = 4 aData(7) = 3 aData(8) = 1 aData(9) = 2 End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim iPass As Integer Dim iTemp As Integer Dim i As Integer For iPass = 1 To 9 For i = 0 To 8 If aData(i) > aData(i + 1) Then iTemp = aData(i + 1) aData(i + 1) = aData(i) aData(i) = iTemp End If Next Next 'output bubble sorted array Dim stOutput As String For i = 0 To 9 stOutput = stOutput & aData(i) & vbNewLine Next MsgBox(stOutput) End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim iPass As Integer Dim iTemp As Integer Dim i As Integer Dim bSwap As Boolean For iPass = 1 To 9 For i = 0 To 8 If aData(i) > aData(i + 1) Then iTemp = aData(i + 1) aData(i + 1) = aData(i) aData(i) = iTemp bSwap = True End If Next If bSwap = False Then Exit For Else bSwap = False End If Next 'output bubble sorted array Dim stOutput As String For i = 0 To 9 stOutput = stOutput & aData(i) & vbNewLine Next MsgBox(stOutput) End Sub End Class