Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with BUBBLE SORT

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
im looking for a simular program as "BUBBLE FORMAT" and "4 # SORT" these arent very clear responses though. I need to organize 4 #'s as well. can someone please help me? i have been trying this for a number of days now... and well, I AM STUMPED

PLEASE HELP

thanx
 
The concept of the bubble sort is simple: you go through all of the numbers you have, and at each point, you check each number against the one right after it. If the one after it is not larger, then you swap them so that it is. Eventually, you will hit the largest number, and you will end up swapping every single time, and when you hit the end of the list, the largest number will be in position. You then repeat on all of the remaining numbers, and so on, until you have "bubbled" the largest number up to the top once for every single number. The list of numbers is then in order. Here's what it looks like in code:

[tt]FOR i% = maxnumber% TO 1 STEP -1
FOR j% = 1 TO i% - 1
IF array(j%) > array(j% + 1) THEN SWAP array(j%), array(j% + 1)
NEXT j%
NEXT i%[/tt]

There are other, much more efficient ways of sorting sequences of numbers, such as the quicksort. Here is a quick comparison table between the two:

[tt] elements bubblesort quicksort analysis
-----------------------------------------------------------
1 0.00000001 0.00000003 bubblesort 3 times faster
10 0.00000100 0.00000100 same speed
100 0.00010000 0.00003321 quicksort 3 times faster
1,000 0.01000000 0.00110352 quicksort 9 times faster
10,000 1.00000000 0.03665816 quicksort 27 times faster
100,000 100.000000 1.21775777 quicksort 82 times faster
1,000,000 10,000.000 40.4530376 quicksort 247 times faster[/tt]

Here is code for the quicksort, with no explanation:

[tt]SUB sort(array(), start%, finish%)
pivot% = start%
pivotvalue = array(pivot%)
FOR i% = start% + 1 TO finish%
IF array(i%) < pivotvalue THEN
array(pivot%) = array(i%)
array(i%) = array(pivot% + 1)
array(pivot% + 1) = pivotvalue
pivot% = pivot% + 1
END IF
NEXT i%
IF pivot% - start% >= 2 THEN sort array(), start%, pivot% - 1
IF finish% - pivot% >= 2 THEN sort array(), pivot% + 1, finish%
END SUB[/tt]

I can explain this code if you want me to. It does use recursion, but the concept is not hard to grasp.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top