Aide

Hello everyone,

I'm new in VBA and i want to solve the following problem:

  • Write a sub that creates an array of 20 random integer numbers ranging from 1 to 100, and sorts it using a bubble sort.
  • Note that at the end of a loop the last element is always sorted. Use this fact to optimize the sort program.
  • Modify the program such that the size of the array is given by the user (in an input box). Use dynamic arrays.

And i wrote the following code but it doesn't work. Please, correct what i've wrote

Option Explicit

' Return a random integer number between two bounds

' It is assumed that lower <= upper.

Function Random(lower As Long, upper As Long) As Long

Random = Int((upper - lower + 1) * Rnd() + lower)

End Function

Sub subblesort()

'Create an array of 20 random integer number

Dim i As Double

Dim nb As Double

Dim myarray() As Variant

nb = 20

For i = 1 To nb

myarray(i) = Random(1, 100)

Next i

'Sort this array using bubblesort

Dim intTemp As Integer

Dim blnExchangeMade As Boolean

blnExchangeMade = True

Do While blnExchangeMade

blnExchangeMade = False

For i = LBound(myarray) To (UBound(myarray) - 1)

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

' exchange the items

intTemp = myarray(i)

myarray(i) = myarray(i + 1)

myarray(i + 1) = intTemp

blnExchangeMade = True

End If

Next

Loop

'This procedure allows the user to choose the size of array

nb = InputBox("Please choose the size of your array wanted")

ReDim myarray(nb)

Call bubblesort

End Sub

Bonjour

En Français c'est mieux

A tester

In French it is better

A test

Option Explicit

' Return a random integer number between two bounds
' It is assumed that lower <= upper.
Function Random(lower As Long, upper As Long) As Long
  Random = Int((upper - lower + 1) * Rnd() + lower)
End Function

Sub subblesort()
'Create an array of 20 random integer number
Dim i As Double
Dim nb As Double
Dim myarray() As Variant

  nb = 20

  'This procedure allows the user to choose the size of array
  nb = InputBox("Please choose the size of your array wanted", Default:=nb)

  ReDim myarray(nb)

  For i = 1 To nb
    myarray(i) = Random(1, 100)
  Next i

  'Sort this array using bubblesort

Dim intTemp As Integer
Dim blnExchangeMade As Boolean

  blnExchangeMade = True

  Do While blnExchangeMade

    blnExchangeMade = False

    For i = LBound(myarray) To (UBound(myarray) - 1)
      If myarray(i) > myarray(i + 1) Then
        ' exchange the items
        intTemp = myarray(i)
        myarray(i) = myarray(i + 1)
        myarray(i + 1) = intTemp
        blnExchangeMade = True
      End If
    Next
  Loop

End Sub

Merci beaucoup pour votre aide, sa marche maintenant

Rechercher des sujets similaires à "aide"