Sorting an Array on the Commodore 64

Published: April 1, 2018, 2:17 p.m.

b'
\\nIn this episode I’ll demonstrate how to sort a numeric array on the Commodore 64. The same principle works for string arrays, and of course on all other Commodore BASIC computers.
\\nThe technique I’m using here is called Bubble Sort: in effect we’re comparing the first two items in the array, and if the left one is larger than the right one, the values are swapped around. This loop continues until all items in the array have been compared and sorted (hence the smallest items “bubble” to the front of the array, much like the smallest bubbles in a soda float to the top first).
\\nHere’s the full code I’m building, including the lottery portion. The Bubble Sort code starts in line 200.
\\n10 x=rnd(-ti)
\\n20 for i=1 to 6
\\n30 rn=int(rnd(1)*49)+1
\\n40 for j=1 to i
\\n50 if n(j)=rn then 30
\\n60 next j
\\n70 n(i)=rn
\\n80 next i
\\n100 print:gosub 200
\\n110 for i=1 to 6
\\n120 print n(i);
\\n130 next
\\n140 print
\\n199 goto 20
\\n200 rem bubble sort
\\n210 for i=5 to 1 step -1
\\n220 for j=1 to i
\\n230 x=n(j):y=n(j+1)
\\n240 if x>y then n(j)=y:n(j+1)=x
\\n250 next:next
\\n299 return
\\nI’ve explained how to build the lottery generator in this code here: https://wpguru.co.uk/2018/03/how-to-generate-lottery-numbers-on-the-commodore-64/
\\nHappy retro hacking!
'