Visual Basic - Lösning Lab 14-1

Option Explicit
Dim vektor() As Integer 'Håller reda på talen
Dim antal As Integer 'Antal tal som ska skapas och sorteras
Dim antalByten As Integer 'Hur många byten som har gjorts

Private Sub cmdSkapa_Click()

'Läs av hur många som ska skapas
antal = Val(cmbAntal.Text)

'Reservera minne för vektorn
ReDim vektor(antal)

'Generera slumptalen från 0 till 9
Dim i As Integer
For i = 1 To antal

vektor(i) = Int(Rnd * 9) + 1

Next i

'Rensa listan
lstResultat.Clear

'Nollställ antal byten
antalByten = 0

'Visa de osorterade talen
Call Visa

End Sub

Private Sub cmdSortera_Click()

'Genomför bubbelsortering

'Loopvariabler
Dim i As Integer

'Håller reda på om någon förändring skett
Dim bytt As Boolean

'Jämför tal så länge som...
Do
bytt = False

For i = 1 To antal - 1

If vektor(i) > vektor(i + 1) Then

Dim tmp As Integer
tmp = vektor(i)
vektor(i) = vektor(i + 1)
vektor(i + 1) = tmp

bytt = True
antalByten = antalByten + 1

Call Visa

End If
Next i

Loop While bytt '...några tal byter plats

End Sub

Private Sub Visa()

'Skapa en sträng med alla talen i vektorn
Dim talen As String
Dim i As Integer
For i = 1 To antal

talen = talen + " " + Str(vektor(i))

Next i

'Lägg till vilken "flytt" det är
talen = talen + " (" + Str(antalByten) + " )"

'Lägg till strängen med tal i listan
lstResultat.AddItem talen

'Visa antal byten
lblAntalByten = Str(antalByten)

End Sub

Private Sub mnu10_Click()

cmbAntal.Text = "10"
Call cmdSkapa_Click

End Sub

Private Sub mnu5_Click()

cmbAntal.Text = "5"
Call cmdSkapa_Click

End Sub

Private Sub mnu50_Click()

cmbAntal.Text = "50"
Call cmdSkapa_Click

End Sub

Private Sub mnuAvsluta_Click()

End

End Sub

Private Sub mnuSorteraTalen_Click()

Call cmdSortera_Click

End Sub