Log In  

Hi,

I've written a bubble-sort function snippet, which might be helpful for others.

Function takes a list as an argument, and directly modifies that list.

Pico-8 treats the first index as 1 as opposed to 0, so a lot of standard code snippets have to be tweaked to work. Please correct if you see any errors or ways to increase efficiency.

-ElectricGryphon

function bsort(list)
 local i
 local j
 local temp
 local swapped = false

 local n=len(list)

 --problems with 1 based index

 for i=1,n
  do
   swapped = false
   for j=2,n-i+1
     do
     if( list[j]<list[j-1])
      then
       temp=list[j]
       list[j]=list[j-1]
       list[j-1]=temp
       swapped = true
      end
    end
    if(swapped==false)then  return end
  end
end 
P#14709 2015-09-28 11:36 ( Edited 2015-09-28 17:04)

Some notes:

  • You don't need to pre-declare your values like you do in old ISO C code. It makes it a bit easier to read and uses less tokens if you declare them when they are first defined.
  • Instead of '(swapped == false)' you can just do 'not swapped' and save several tokens.
  • Lua can do multiple assignment which lets you swap values without needing a temporary variable. (ex: 'a, b = b, a')

Also, somebody posted an [insertion sort]( https://www.lexaloffle.com/bbs/?tid=2477) implementation which is much shorter. Both algorithms work very well for a list that is either short or resorted each frame without changing very much.

P#14711 2015-09-28 13:04 ( Edited 2015-09-28 17:05)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 15:58:27 | 0.004s | Q:8