Thread: array sorting

    #1
  1. No Profile Picture
    hum...
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Location
    Brazil
    Posts
    24
    Rep Power
    0

    Question array sorting


    I need a array with x numbers (1 to x) mixed. Like this:

    Using 4 numbers (1 to 4), i need:

    array(1) = 3
    array(2) = 2
    array(3) = 4
    array(4) = 1

    This is random. I make this:

    Code:
    x = 4
    randomize
    
    array(1)=Int((x) * Rnd + 1)
    
    array(2)=Int((x) * Rnd + 1)
    while array(2) = array(1)
    	array(2)=Int((x) * Rnd + 1)
    wend
    
    array(3)=Int((x) * Rnd + 1)
    while (array(3) = array(2)) or (array(3) = array(1))
    	array(3)=Int((x) * Rnd + 1)
    wend
    
    array(4)=Int((x) * Rnd + 1)
    while (array(4) = array(3)) or (array(4) = array(2)) or (array(4) = array(1))
    	array(4)=Int((x) * Rnd + 1)
    wend
    But, in this case, if x is a big number (like 100), the code will be very big too...
    Any idea?

    Thanks in advance

    Ricardo
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2001
    Location
    NJ
    Posts
    428
    Rep Power
    17
    lets see if i remember by bubble sort from my programming classes in school

    PHP Code:
    function BubbleSort(arr)
      for 
    0 to uBound(arr
         for 
    i to Ubound(arr
            if 
    arr(a) < arr(ithen
             
    'swap values
             tmp = arry(i)
             arr(i) = arr(a) 
             arr(a) = tmp
           end if 
         next 
      next 
     BubbleSort = arr
    end function 
    I just tested it and it works. if you do a search on google for bubble sort it will tell you how it works. Basicall it finds the lowest value and puts it in the 1st index position, then the second lowest and puts it in the second index position and so on. This is a pretty effective way to sort an array and pretty common.
    Last edited by imbrokn; May 20th, 2003 at 10:05 AM.
  4. #3
  5. No Profile Picture
    hum...
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Location
    Brazil
    Posts
    24
    Rep Power
    0
    Sorry, I didn't express myself well.
    I want a array with shuffled numbers, and not ordened numbers. The array contains numbers, 1 to x, ordered randomly (each time the order is different), like in my code (above).

    Thank you

    Regards,
    Ricardo

IMN logo majestic logo threadwatch logo seochat tools logo