Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

The goal of this Code Golf is to create a program that sorts a list of strings (in ascending order), without using any built-in sort method (such as Array.Sort() in .NET, sort() in PHP, ...). Note that this restriction excludes using a built-in method that sorts an array descending, and then reversing the array.

Some details:

  • Your program should prompt for input, and this input is a list of strings containing only ASCII lower-case alphabetic characters a-z, comma-separated without spaces. For example:

    code,sorting,hello,golf
    
  • The output should be the given list of strings, but sorted in ascending order, still comma-separated without spaces. For example:

    code,golf,hello,sorting
    
share|improve this question
add comment

14 Answers

up vote 7 down vote accepted

Ruby 76 54 51 chars

x=gets.scan /\w+/;$><<x.dup.map{x.delete(x.min)}*?,
share|improve this answer
1  
Very nice, bogosort :D –  Doorknob Oct 14 '13 at 19:36
1  
Wow, now it's even more interesting! I had to look at this for a while before I realized what was happening. I suppose now it's a slight variation of selection sort :P –  Doorknob Oct 15 '13 at 12:39
1  
Since the items are guaranteed to be alpha characters: x=gets.scan /\w+/ –  Steven Rumbalski Oct 15 '13 at 15:25
    
Awesome, thanks! –  Tyler Holien Oct 15 '13 at 15:31
add comment

k (16 chars)

Probably doesn't really live up to the spirit of the problem. In k, there is no built in sort operator. <x returns a list of indices of items in x in sorted order.

{x@<x}[","\:0:0]
share|improve this answer
    
Well, this is a kind of built-in sorting, so unfortunately, I can't mark this as answer. I like the idea, however, so +1! –  ProgramFOX Oct 19 '13 at 16:56
add comment

Ruby, 99 chars (Gnome sort)

a=gets.scan /\w+/
p=1
while a[p]
a[p]>a[p-1]?p+=2:(a[p],a[p-1]=a[p-1],a[p])
p-=1if p>1
end
$><<a*?,

This just barely beats my bubble sort implementation:

Ruby, 110 104 101 chars (Bubble sort)

s=gets.scan /\w+/
(z=s.size).times{(0..(z-2)).map{|i|s[i],s[i+1]=s[i+1],s[i]if s[i]>s[i+1]}}
$><<s*?,

This does list.length iterations, because worst-case scenario takes list.length - 1 iterations and one more really doesn't matter, and saves 2 chars.

Just for fun, a Quicksort version:

Ruby, 113 chars (Quicksort)

q=->a{if a[1]
p=a.shift
l=[]
g=[]
a.map{|x|(x>p ?g:l).push x}
q[l]+[p]+q[g]
else
a
end}
$><<q[gets.scan /\w+/]*?,
share|improve this answer
add comment

PHP 83 bytes

<?for($x=fgetcsv(STDIN);$x;)${$x[0]>min($x)?x:a}[]=array_shift($x)?><?=join(~Ó,$a);

An O(n3) implementation of a selection sort. The Ó is character 211; a bit-inverted comma.

Sample usage:

$ more in.dat
code,sorting,hello,golf

$ php list-sort.php < in.dat
code,golf,hello,sorting
share|improve this answer
add comment

Python 3 (80 chars)

l=input().split(',')
m=[]
while l:m+=[l.pop(l.index(min(l)))]
print(','.join(m))

Here is a variation of the while-statement that is of equal length:

while l:x=min(l);m+=[x];l.remove(x)
share|improve this answer
add comment

Mathematica 66 56

Row[#[[Ordering@#]]&[InputString[]~StringSplit~","],","]

Some other solutions without the build-in symbol Ordering:

Bogosort: 84 74

NestWhile[RandomSample,InputString[]~StringSplit~",",!OrderedQ@#&]~Row~","

Bubble Sort: 93 83

Row[InputString[]~StringSplit~","//.{x___,i_,j_,y___}/;j~Order~i==1:>{x,j,i,y},","]

Another solution as inefficient as bogosort: 82 72

#~Row~","&/@Permutations[InputString[]~StringSplit~","]~Select~OrderedQ;
share|improve this answer
add comment

vba, 165

Sub q()
c=","
s=InputBox("?")
Z=Split(s, c)
t=UBound(Z)
For i=1 To t-1
For j=i To t
If Z(i)>Z(j) Then a=Z(i):Z(i)=Z(j):Z(j)=a
Next
Next
Debug.Print Join(Z,c)
End Sub
share|improve this answer
    
I count 165 characters... –  Doorknob Oct 14 '13 at 19:35
    
@Doorknob, fixed count... The greasemonkey script evidently gave me the wrong count as I was typing in the code. –  Sean Cheshire Oct 14 '13 at 19:41
    
You can get rid of a space in that Split. –  minitech Oct 17 '13 at 14:56
add comment

javascript 128

a=prompt().split(',');b=[];for(i in a){b.push(a[i]);k=0;for(j in b){j=k;b[j]>a[i]?[c=b[j],b.splice(j,1),b.push(c)]:k++}}alert(b)

DEMO fiddle.

i am looking for a way to eliminate b.

share|improve this answer
    
Remove the [] around the part after the ? to save 2 chars –  Doorknob Oct 15 '13 at 20:24
    
@Doorknob i have tried it before i get SyntaxError: missing : in conditional expression because ?:; (the shorthand if/else) is only supposed to take two pecies of code to execute (i.e. true?b++:b--;) using [,] is a hack, im still not sure why it works, i think its understood as a empty array declaration, like placing a random string or number as a stand-alone command. but you can still feel free to upvote. –  tryingToGetProgrammingStraight Oct 15 '13 at 22:53
    
Hmm, I suppose I was mistaken. The comma operator can execute multiple pieces of code at once. Using parenthesis works, so I suppose the ?: operator's precedence is lower than , –  Doorknob Oct 16 '13 at 1:45
    
No, did you try? Parenthesis still work... –  Doorknob Oct 16 '13 at 12:14
    
@Doorknob your right, however i tried {,} and it didnt work - i get SyntaxError: missing : after property id. as for precedence parentheses is always first. i still would like a upvote.... –  tryingToGetProgrammingStraight Oct 16 '13 at 12:27
show 1 more comment

R

Bubble Sort: 122 118 characters

a=scan(,"",sep=",");h=T;while(h){h=F;for(i in 1:(length(a)-1)){j=i+1;if(a[i]>a[j]){a[j:i]=a[i:j];h=T}}};cat(a,sep=",")

Bogosort: 100 characters

a=scan(,"",sep=",");while(any(apply(embed(a,2),1,function(x)x[1]<x[2]))){a=sample(a)};cat(a,sep=",")
share|improve this answer
add comment

SED, 135

s/.*/,&,!,abcdefghijklmnopqrstuvwxyz/;:;s/\(,\([^,]*\)\(.\)[^,]*\)\(.*\)\(,\2\(.\)[^,]*\)\(.*!.*\6.*\3\)/\5\1\4\7/;t;s/^,\(.*\),!.*/\1/

Based on my previous sorting entry

share|improve this answer
add comment

Perl, 159

perl -F"," -lape "$m=$m<length()?length():$m for@F;$_{10**(2*$m)*sprintf'0.'.'%02d'x$m,map-96+ord,split//}=$_ for@F;$_=join',',map$_{$_+0},grep exists$_{$_+0},'0'.1..'0'.10**100"

This never stood a chance to win, but decided to share it because I liked the logic even if it's a mess :) The idea behind it, is to convert each word into an integer (done using the ord function), we save the number as a key in a hash and the string as a value, and then we iterate increasingly through all integers (1..10**100 in this case) and that way we get our strings sorted.

WARNING: Don't run this code on your computer, since it loops through trillions+ of integers. If you want to test it, you can lower the upper range limit and input non-lengthy strings. If for any reason this is against the rules, please let me know and I'll delete the entry!

share|improve this answer
add comment

Haskell, 171

import Data.List
f=filter
s[]=[]
s(p:r)=s(f(<p)r)++[p]++s(f(>p)r)
t[]=[]
t s=takeWhile(/=',')s:t(drop 1$dropWhile(/=',')s)
main=do;l<-getLine;putStrLn$intercalate","$s$t l

At least it’s… sort of efficient.

share|improve this answer
add comment

JS: 107 chars - Bubble Sort

a=prompt().split(/,/);for(i=a.length;i--;)for(j=0;j<i;)a[j]>a[j+1]?[b=a[j],a[j]=a[++j],a[j]=b]:j++;alert(a)

I looked at @tryingToGetProgrammingStraight's answer and tried to improve it, but ended up implementing it slightly differently.

share|improve this answer
add comment

MATLAB - 29 (Miracle sort)

while !issorted(A) do
end_while

Explanation:

Since computers are not perfect, the chance of a bit arbitrarily swapping for no reason is non-zero. Therefore by the infinite monkey theorem, if you keep checking if the array is sorted, it will be eventually.

share|improve this answer
    
And I thought bogosort was a bad algorithm. –  Kevin Cox Nov 22 '13 at 4:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.