Log In  

A slow but token-efficient sort:

-- 35-token bubblesort, by pancelor
function sort(arr)
  for i=1,#arr do
    for j=i,#arr do
      if arr[j] < arr[i] then
        add(arr,deli(arr,j),i) --slow swap
      end
    end
  end
end

I did a brief speed analysis and this function seems reasonable to use for arrays up to around 50 or 100 elements, depending on how much CPU you have available to burn.

speed analysis:


I did some minimal testing, using this code:

cls()
function _draw()
arr={
--20,5,8,3,7,4,1,9,2,-30,
--20,5,8,3,7,4,1,9,2,-30,
--20,5,8,3,7,4,1,9,2,-30,
--20,5,8,3,7,4,1,9,2,-30,
20,5,8,3,7,4,1,9,2,-30,
}
sort(arr)
end

By commenting out lines of the array, I changed it's length. Here's how much CPU the function spent, as a percentage of a single 30fps frame (measured with the ctrl-p monitor, on pico8 0.2.5g)

The "best case cpu" was calculated by defining arr outside of _draw, so that the array was already sorted after the first frame

Array length Typical cpu (30fps) Best case cpu (30fps)
10 0% 0%
20 1% 1%
50 5% 4%
100 21% 15%
200 81% 58%
300 181% 130%
400 321% 231%

I believe this algorithm is O(n^3): O(n^2) for the two loops, and an additional O(n) b/c the swap step uses add and deli, which shift around the array elements. But the chart seems to indicate that doubling the length will quadruple the cpu cost (instead of octupling it) so maybe it's only O(n^2) somehow? It doesn't much matter, since you don't want to use this for large arrays anyway, but maybe add/deli are cheaper than I would expect.

P#128863 2023-04-21 23:04

3

I found a sorting implementation that's 1 token cheaper (34 tokens), and slightly better cpu wise - based on this simple and surprising sorting algorithm: https://arxiv.org/pdf/2110.01111.pdf

function sort(arr)
 for i,arri in inext,arr do
  for j,arrj in inext, arr do
   if arri<arrj then
    arri,arr[i],arr[j]=arrj,arrj,arri
   end
  end
 end
end

complexity is clearly n^2, and also a bit better cpu wise on your tests (for 200 elements, 0.6 compared to 0.8 with yours)

pretty stoked to find a use for this niche algorithm, but i wouldn't be surprised if it's possible to do better token wise, perhaps with some add/del tricks like your alg does

P#128965 2023-04-24 18:44

oh, I recognized that sort before I clicked the link! I love it, it's so funny.

the add/deli trick doesn't work as-is unfortunately -- it requires i<=j. that's why I didn't look into using your sort, but clearly I should have -- nice token savings!

P#128975 2023-04-24 22:13

[Please log in to post a comment]