Problem of the Day
A new programming or logic puzzle every Mon-Fri

Insertion Sort Golf

Today's problem is a fun one. We'll take the classic algorithm, insertion sort, and see who can implement it correctly with the fewest bytes of code. Each character and new line counts as a byte of code for this exercise. The list you're sorting doesn't count towards the overall byte count. Can you get below 100?

Permalink: http://problemotd.com/problem/insertion-sort-golf/

Comments:

  • Anonymous - 9 years, 9 months ago

    Got it down to 105 bytes so far

    def i(l):
     for s in range(1,len(l)):e=l.pop(s);l.insert(__import__('bisect').bisect(l[:s],e),e)
     return l
    

    reply permalink

  • David - 9 years, 8 months ago

    I'm sure someone with more code golf experience than me could shave off a few more characters here or there. Especially if taking advantage of various compiler exploits. Adding main, mine still compiles with Sublime's default C compiler.
    I'm stuck at 112 relevant bytes. Readability:

    int i,j;
    int*S(int* l, int s){
    for(;i<s;)
      for(j=i++;j>0&l[j-1]>l[j];)
        l[j-1]^=l[j]^=l[j-1],l[j--]^=l[j-1];
        return l;
    }
    

    Minimized

    int i,j;int*S(int* l, int s){for(;i<s;)for(j=i++;j>0&l[j-1]>l[j];)l[j-1]^=l[j]^=l[j-1],l[j--]^=l[j-1];return l;}
    

    reply permalink

Content curated by @MaxBurstein