12-12-2013, 02:26 PM
Hi everyone,
This small program takes a list in the stack and returns the sorted list using the bubble sort algorithm.
'T.BUL'
Bubble sort is not very efficient as sorting method, but the algorithm is simple to understand.
Another method more efficient is the selection sort:
'T.SEL'
One more, with insertion method this time !
'T.INS'
Damien.
This small program takes a list in the stack and returns the sorted list using the bubble sort algorithm.
Code:
« DUP SIZE
IF DUP 1 > THEN 2
FOR i 1 i 1 -
FOR j DUP j GET OVER j 1 + GET
IF DUP2 > THEN ROT j ROT PUT j 1 + ROT PUT
ELSE DROP2 END
NEXT
- 1 STEP
ELSE DROP
END
»
Bubble sort is not very efficient as sorting method, but the algorithm is simple to understand.
Another method more efficient is the selection sort:
Code:
« DUP SIZE
IF DUP 1 > THEN 2
FOR i DUP 1 GET 1 → aide k
« 2 i FOR j DUP j GET IF DUP aide > THEN
'aide' STO j 'k' STO ELSE DROP END
NEXT k OVER i GET PUT i aide PUT
»
-1 STEP
ELSE DROP
END
»
One more, with insertion method this time !
Code:
« DUP SIZE
IF DUP 1 > THEN → n
« 2 n FOR i DUP i GET i 1 -
→ aide j
« WHILE DUP j 1 MAX GET aide > j 1 ≥ AND
REPEAT j 1 - 'j' STO
END
IF j i 1 - < THEN DUP 1 j SUB aide +
OVER j 1 + i 1 - SUB + OVER i 1 + n SUB +
SWAP DROP
END
»
NEXT
»
ELSE DROP END
»
Damien.