Tuesday, 10 January 2017

Bubble Sort

The bubble sort is used to sort a list of numbers. It works by comparing pairs of numbers and swapping them if necessary. It means that after each iteration the next largest number in the sequence will go to the top.

Original=       1  2   7  4  5
1st Iteration= 1  2   4  5  7

You continue going through each iteration until no swaps are made. Then it is complete.

Pseudocode

Repeat
Swapped= false
For 1 to (array length) do
If A(i) > A(i + 1) then
temp=A(i)
swap(A(i)=A(i + 1))
A(i + 1) = temp
Swapped = true
End If
End for
until not swapped
End Procedure

VB Code

Module Module1
    Dim num(8) As Integer
    Dim swap As Boolean
    Dim Temp As Integer
    Sub Main()
        num(1) = 2
        num(2) = 1
        num(3) = 4
        num(4) = 8
        num(5) = 6
        num(6) = 5
        num(7) = 7
        num(8) = 3
        Do
            swap = False
            For index = 1 To 8 - 1
                If num(index) > num(index + 1) Then
                    Temp = num(index)
                    num(index) = num(index + 1)
                    num(index + 1) = Temp
                    swap = True
                End If
            Next
        Loop Until swap = False

        For index = 1 To 8
            Console.WriteLine(num(index))
        Next
        Console.ReadLine()
    End Sub
End Module






No comments:

Post a Comment