I think what you are asking is "How do I sort?"

by (Login Mikrondel)
Moderator

The easiest way to sort is to swap things that are in the wrong order. QB has the SWAP statement to help you do this.

With 4 items it's feasible to make a series of IFs and SWAPs that will produce the desired ordering, but with more items it becomes very tedious. Using an array allows you to write a short loop instead, so I will show how it's done.

One of the most obvious sorting techniques is "bubble sort" and the idea behind it is to look through the list, and if you see a pair of items next to each other that are in the wrong order you swap them. Then you repeat the procedure until you no longer find anything out of order.

DIM Idea$(1 to 6)
DIM votes(1 to 6)

Idea$(1) = "May"
votes(1) = 5
Idea$(2) = "the"
votes(2) = 1
Idea$(3) = "Force"
votes(3) = 0
Idea$(4) = "be"
votes(4) = 3
Idea$(5) = "with"
votes(5) = 2
Idea$(6) = "you"
votes(6) = 4

DO

swappedSomething = 0
FOR I = 1 to 5 'Scan through list
IF votes(I+1) > votes(I) THEN 'if adjacent items are out of order
SWAP votes(I), votes(I+1) 'swap them
SWAP Idea$(I), Idea$(I+1)
swappedSomething = 1 'and remember that it was done
END IF
NEXT

LOOP WHILE swappedSomething = 1



Another technique is selection sort, where you go through the list and locate the largest item and put it first, then go through the remaining items and find the largest and put it second, then go through the remaining items and find the largest and put it third, and so on. It looks like this:


FOR I = 1 to 5 'Item we're looking for
FOR J = I+1 to 6 'Go through the rest of the list
IF votes(J) > votes(I) THEN 'This one is larger than what we have currently
SWAP votes(I), votes(J)
SWAP Idea$(I), Idea$(J)
END IF
NEXT
NEXT


You should figure out how at least one of these methods works. You probably haven't seen certain things before so if you have any questions please ask.

Posted on Jan 14, 2011, 7:01 PM

Respond to this message   

Return to Index


Response TitleAuthor and Date
* I don't think that is the sort of thing he was looking for. :) on Jan 14
 *He did say "from favorite to least preferred" on Jan 15
  Ah, but you have to walk before you can run.... on Jan 15
  * You can't sort one till ya know what it is...Clippy Sort on Jan 15
   Now wonderingif if Dan's last name is Phool? on Jan 15
    * It's nothing personal Dan....:-P on Jan 15
     My bit and Clippy's comment is from an American commercial...URL* on Jan 16
      *Very funny -- now my mnemonic device for you is re-Pete. on Jan 16
       * Well that's just way too Bobvious. on Jan 16
   *You were the one suggesting TWO of them :P on Jan 15
heavy-duty non-recursive quicksort on Jan 18
 *What a curious sense of humour you have :P on Jan 19
  * What is so funny Art?Clippy on Jan 19
  * yeah, this is SORT of funny, i mean the heavy-duty part on Jan 19