Post by tsh73 on Apr 3, 2018 8:28:39 GMT
There is insertion sort popped up in our curriculum so I went and compared some sorts I thought I knew.
Namely insertion sort, select sort and bubble sort.
Interesting thing - I checked Wikipedia after and see that all my implementations differ from Wikipedia ones!
Like, select sort works by finding max instead of min
insertion sorts touches 0-th item of array so it wouldn't work with array starting from 0
(and adding IF/EXIT WHILE for "out of array" check significantly slows it down!)
Though I pretty sure insertion sort / select sort work as fast as they could (?)
but bubble sorts in Wikipedia quite differ from my version.
May be they perform significantly better?
Namely insertion sort, select sort and bubble sort.
Interesting thing - I checked Wikipedia after and see that all my implementations differ from Wikipedia ones!
Like, select sort works by finding max instead of min
insertion sorts touches 0-th item of array so it wouldn't work with array starting from 0
(and adding IF/EXIT WHILE for "out of array" check significantly slows it down!)
Though I pretty sure insertion sort / select sort work as fast as they could (?)
but bubble sorts in Wikipedia quite differ from my version.
May be they perform significantly better?
'bubbleSort vs select vs insertion sort
N=300
'N=10
s=0.5
randomize s 'if you want them to be the same
dim a(N)
dim b(N)
print "N=";N
print "tInsertion", "tSelect","tBubble", "ins/bubble","sel/bubble"
for nExp=1 to 20
scan
'generate
for i = 1 to N
b(i)=int(rnd(0)*900)+100'-500
next
'prepare
for i = 1 to N
a(i)=b(i)
next
'print "src"
'gosub [printArr]
[bubbleSort]
'prepare
for i = 1 to N
a(i)=b(i)
next
t0=time$("ms")
for j=N-1 to 1 step -1 'number of pairs
for i = 1 to j
if a(i)> a(i+1) then tmp=a(i):a(i)=a(i+1):a(i+1)=tmp
next
'gosub [printArr]
next
tBubble=time$("ms")-t0
[selectSort]
'prepare
for i = 1 to N
a(i)=b(i)
next
t0=time$("ms")
for j=N to 2 step -1 'unsorted length
maxPos=1:maxItem=a(1) 'find the max in unsorted
for i = 2 to j
if a(i)> maxItem then maxItem=a(i):maxPos=i
next
a(maxPos)=a(j):a(j)=maxItem 'swap it with last unsorted
'gosub [printArr]
next
tSelect=time$("ms")-t0
[insertion]
'prepare
for i = 1 to N
a(i)=b(i)
next
t0=time$("ms")
for j=2 to N '1 is sorted, start with 2
i=j
' while a(i)<a(i-1) 'works only if a(0) less them min(a())
tmp=a(i)
while (tmp<a(i-1)) AND (i>1) 'touches a(0) (so from 0 will not work) but not uses it
a(i)=a(i-1)
i=i-1
wend
a(i)=tmp
'gosub [printArr]
next
tInsertion=time$("ms")-t0
'print "res"
'gosub [printArr]
print tInsertion, tSelect, tBubble, int((tInsertion/tBubble)*100);"%",int((tSelect/tBubble)*100);"%"
s1=s1+tInsertion
s2=s2+tSelect
s3=s3+tBubble
next 'experiment
print "-- avg --------------------"
print int(s1/20), int(s2/20), int(s3/20), int((s1/ s3)*100);"%", int((s2/ s3)*100);"%"
end
[printArr]
for p.i=1 to N
print a(p.i);" ";
next
print
return