Results 1 to 2 of 2

Thread: Sort Array of numbers

  1. #1

    Thread Starter
    Fanatic Member BenJones's Avatar
    Join Date
    Mar 2010
    Location
    Wales UK
    Posts
    637

    Sort Array of numbers

    Hi this something I came up with to sort a basic array of numbers.
    and I thought I share it with the rest in the hope it come in useful.

    vb Code:
    1. Private Sub Swap(a As Variant, b As Variant)
    2. Dim t As Variant
    3.     'Swap a and b
    4.     t = a
    5.     a = b
    6.     b = t
    7. End Sub
    8.  
    9. Private Sub Sort(arr As Variant)
    10. Dim X As Long, Y As Long, Size As Long
    11. On Error Resume Next
    12.  
    13.     'Get array size
    14.     Size = UBound(arr)
    15.    
    16.     'Do the sorting.
    17.     For X = 0 To Size
    18.         For Y = X To Size
    19.             If arr(Y) < arr(X) Then
    20.                 'Swap vals
    21.                 Call Swap(arr(X), arr(Y))
    22.             End If
    23.         Next Y
    24.     Next X
    25. End Sub

    Example

    vb Code:
    1. Private Sub Command1_Click()
    2. Dim Nums(0 To 5) As Variant
    3.     'Add some random numbers.
    4.     Nums(0) = 4
    5.     Nums(1) = 2
    6.     Nums(2) = 6
    7.     Nums(3) = 3
    8.     Nums(4) = 5
    9.     Nums(5) = 0.1
    10.    
    11.     Call Sort(Nums)
    12.     'Display sorted results.
    13.     MsgBox Nums(0)
    14.     MsgBox Nums(1)
    15.     MsgBox Nums(2)
    16.     MsgBox Nums(3)
    17.     MsgBox Nums(4)
    18.     MsgBox Nums(5)
    19. End Sub

  2. #2
    PowerPoster
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    2,579

    Re: Sort Array of numbers

    Your method is known as Bubble sort it is suitable for array with small items. for big size array there are many other methods which is very fast and very complex too. See this topic



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width