| Bytes | Lang | Time | Link |
|---|---|---|---|
| nan | 180504T215851Z | sergiol | |
| 085 | JavaScript V8 | 250505T021229Z | Steve Be |
| 046 | R | 250326T204320Z | Glory2Uk |
| 092 | APLNARS | 250326T174921Z | Rosario |
| 070 | ruby plaF | 180504T212350Z | histocra |
| 077 | Perl 5 | 180501T150709Z | Xcali |
| 119 | Ceylon Bogosort | 180501T135914Z | PaΕlo Eb |
| 073 | Python 3.5+ | 171116T210623Z | Antti Ha |
| 2430 | πΌππππ | 160207T034324Z | Mama Fun |
| 025 | GolfScript | 150606T025357Z | Dennis |
| 101 | Swift | 160206T193633Z | Palle |
| 141 | Haskell | 131016T190501Z | Ry- |
| 122 | Scala | 150606T020011Z | gan_ |
| 134 | Java | 150604T212416Z | SuperJed |
| 056 | Mathematica | 131017T072924Z | alephalp |
| 107 | JS | 131016T200536Z | Dom Hast |
| 159 | Perl | 131016T130102Z | psxls |
| 099 | Ruby | 131014T175927Z | Doorknob |
| 051 | Ruby | 131014T184747Z | Tyler Ho |
| 080 | Python 3 | 131015T151442Z | Steven R |
| 135 | SED | 131015T121039Z | Hasturku |
| nan | 131015T073556Z | plannapu | |
| 083 | PHP | 131015T111128Z | primo |
| 128 | javascript | 131014T213707Z | Math chi |
| 165 | vba | 131014T185405Z | SeanC |
| 016 | k | 131014T180151Z | skeevey |
Reusing my own answer on Sort an Integer List
Tcl, 190 bytes
set L [split [gets stdin] ,]
time {set x 0
while \$x<[incr i] {if {[set n [lindex $L $i-1]]<[lindex $L $x]} {set L [lreplace [linsert $L $x $n] $i $i]}
incr x}} [llength $L]
puts [join $L ,]
JavaScript (V8), 85 bytes
for(a=prompt().split`,`,i=0;s=a[i],n=a[i+1];s>n?[a[i],a[i+1],i]=[n,s,0]:i++);alert(a)
This code runs as a program in a browser console, taking input with prompt, and outputting the result with alert.
I think this is called a bubble sort?
R, 46 bytes
x=scan(,"");while(is.unsorted(x))x=sample(x);x
Randomly shuffles the words until they are sorted.
APL(NARS), 92 chars
{{>/kββaβ³βΒ¨βΊβ΅:Β―1β=/k:0β1}{1β₯rββ’β΅:,β΅βpββ΅ββ¨βrΓ·2β(βΊβΊβββ΅/β¨0<k),(β΅/β¨0=k),βΊβΊβββ΅/β¨0>kββΊβΊ{β΅βΊβΊp}Β¨β΅}β΅}
It would use one quicksort that use one compare function on two elements of
the input array (that are two string): {>/kββaβ³βΒ¨βΊβ΅:Β―1β=/k:0β1} as the
qsort of C language. I rewrote that from APL answer of RosettaCode for
quicksort. I don't know if it is ok, because few or no test or use.
test:
fβ{{>/kββaβ³βΒ¨βΊβ΅:Β―1β=/k:0β1}{1β₯rββ’β΅:,β΅βpββ΅ββ¨βrΓ·2β(βΊβΊβββ΅/β¨0<k),(β΅/β¨0=k),βΊβΊβββ΅/β¨0>kββΊβΊ{β΅βΊβΊp}Β¨β΅}β΅}
f('code')('sorting')('hello')('golf')
β4βββββββββββββββββββββββββββββββββββ
ββ4βββββ β4βββββ β5ββββββ β7βββββββββ
ββ codeβ β golfβ β helloβ β sortingββ
ββββββββ βββββββ ββββββββ ββββββββββ2
βββββββββββββββββββββββββββββββββββββ
using the sort function of the language would be more easy
{β΅[ββ΅]}('code')('sorting')('hello')('golf')
β4βββββββββββββββββββββββββββββββββββ
ββ4βββββ β4βββββ β5ββββββ β7βββββββββ
ββ codeβ β golfβ β helloβ β sortingββ
ββββββββ βββββββ ββββββββ ββββββββββ2
βββββββββββββββββββββββββββββββββββββ
and {β΅[ββ΅]} would be 7 chars...
ruby -plaF, , 70 bytes
o=[]
$F.map{|s|i=o;s.bytes{|b|i=i[b]=[*i[b]]};i[0]=s<<?,}
$_=o*''
chop
O(n), if you pretend that resizing and compacting an array is free (it is very not free).
We create a deeply and unevenly nested array o by putting a string with bytes b1,b2...bn into the array at position o[b1][b2]...[bn]. The result looks like [,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,["a,",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, [,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ["abc,"], ["abd,"], ["abe,"]], ["ac,"], ["ad,"]],, ["c,"]]
Then we flatten and output it.
Perl 5, 77 bytes
map{$F[$_]gt$F[$_+1]&&(@F[$_,$_+1]=@F[$_+1,$_])for 0..@F-2}@F;$_=join',',"@F"
Simple bubble sort.
Ceylon (Bogosort), 119
String s(String i)=>",".join([*i.split(','.equals)].permutations.select((p)=>!any{for([x,y]in p.paired)y<x})[0]else[]);
I found the permutations method and thus ended up with Bogosort (a non-random variant).
Formatted and commented:
// a function `s` mapping a String `i` to a String
String s(String i) =>
// the end result is created by joining the iterable in (...).
",".join(
// take the input, split it on commas, make the result a sequence.
[*
i.split(','.equals) // β {String+}
] // β [String+]
// get the iterable of all permutations of this sequence.
// Yes, this is an iterable of O(n!) sequences (though likely
// lazily computed, we don't need all in memory at once).
.permutations // β {[String+]*}
// filter this iterable for ordered sequences.
// Using select instead of filter makes this
// eager instead of lazy, so we are actually iterating
// through all n! sequences, and storing the ordered
// ones. (All of those are equal.)
.select(
// this is our function to check whether this sequence
// is ordered in ascending order.
(p)=>
// return if none of the following iterable of booleans is true.
!any {
// This is a for-comprehension. Inside an named argument list
// (what we have here, although there is no name) for a
// function which wants an iterable, this becomes an iterable,
// lazily built from the existing iterable p.paired,
// which is just an iterable with all pairs of subsequent
// elements.
for([x,y] in p.paired)
// for each such pair, we evaluate this expression, which
// is true when the sequence is not ordered correctly.
y < x // β Boolean
// β {Boolean*}
} // β Boolean
// β Boolean([String+])
) // β [[String+]*]
// we now have a sequence of (correctly sorted) sequences.
// just take the first one.
// If we had used `.filter` before, this would have to be `.first`.
[0] // β [String+]|Null
// in case this is null, which can only happen if the original array was
// empty, so there were no permutations, just use the empty sequence
// again. (Actually, split never returns an empty array, so this can't
// happen, but the type checker can't know that.)
else [] // β [String*]
// so that is what we pass to the join method.
) // β String
;
Without the formatting and parsing it becomes just 90 bytes:
String[]s(String[]i)=>i.permutations.select((p)=>!any{for([x,y]in p.paired)y<x})[0]else[];
Python 3.5+, 73 bytes
This takes inspiration from Steven Rumbalski's answer but uses list comprehension instead of a while loop; the number of iterations comes from the copied list l which is the reason this requires additional unpacking generalizations and Python 3.5
l=input().split(',');print(*[l.pop(l.index(min(l)))for _ in[*l]],sep=',')
πΌππππ, 24 chars / 30 bytes (noncompetitive)
Γ―βΔβͺ;β»Γ―κ)ΞΓΏΡ¨Ε Γ―,β$βΠΖ΅Γ―;Ξ
Using selection sort!
Explanation
Γ―βΔβͺ;β»Γ―κ)ΞΓΏΡ¨Ε Γ―,β$βΠΖ΅Γ―;Ξ // implicit: Γ―=input, Ξ=[]
Γ―βΔβͺ; // split Γ― along commas and set it to Γ―
β»Γ―κ) // while Γ―'s length > 0
ΞΓΏ // push to Ξ:
Ρ¨Ε Γ―,β$βΠΖ΅Γ―; // removed minimum item(s) from Γ― using builtin
Ξ // get sorted array
Basically recursively removes and pushes the minimum from the input to another array.
GolfScript, 26 25 bytes
","/.,{{.2$<{\}*}*]}*","*
Straightfoward implementation of Bubble Sort.
Try it online in Web GolfScript.
How it works
","/ # Split the input string at commas.
., # Get the number of chunks.
{ # Do that many times:
{ # Reduce; for each element but the first:
.2$< # Push 1 if the last two strings are in descending order, 0 if not.
{\}* # Swap these strings that many times.
}*] # Collect the strings dumped by reduce in an array.
}* #
","* # Join, separating by commas.
Swift, 101 bytes
func s(a:[String])->[String]{return a.count<2 ? a:(s(a.filter{$0<a[0]})+[a[0]]+s(a.filter{$0>a[0]}))}
Ungolfed:
//quicksort
func sort(a:[String]) -> [String]
{
//return the array if its length is less than or equal to 1
if a.count <= 1
{
return a
}
//choose the first element as pivot
let pivot = a[0]
//retrieve all elements less than the pivot
let left = a.filter{ $0 < pivot }
//retrieve all elements greater than the pivot
let right = a.filter{ $0 > pivot }
//sort the left partition, append a new array containing the pivot,
//append the sorted right partition
return sort(left) + Array<String>(arrayLiteral: pivot) + sort(right)
}
Haskell, 141
import Data.List
m=minimum
s[]=[]
s l=m l:s(l\\[m l])
t[]=[]
t s=let(a,b)=span(/=',')s in a:t(drop 1 b)
main=interact$intercalate",".s.t.init
At least itβsβ¦ sort of efficient.
Scala, 122 bytes
As a one-liner (88 bytes):
.permutations.filter(_.sliding(2).map(w=>w(0)<w.last).fold(true)((a,b)=>a&&b)).toSeq(0)
(it will sort a list by just doing list.permutations.fil... )
As a program (122 bytes):
println(readLine.split(",").toSeq.permutations.filter(_.sliding(2).map(w=>w(0)<w.last).fold(true)((a,b)=>a&&b)).toSeq(0))
A longer version if you want it to read from stdin.
This iterate over all the permutations of the given list until it stumble on a sorted one. It's not fast as it takes about 12 seconds to sort a 10 elements list and well over a minute for a 11 elements one.
[Edit] items need to be unique or < can be replaced by <=.
Also, sorry for necro.
Java, 134 bytes
A method that implements Gnome Sort.
void s(String[]a){int m=a.length-1,i=0;while(i<m){while(i>=0&&a[i].compareTo(a[i+1])>0){String t=a[i];a[i]=a[i+1];a[i+1]=t;i--;}i++;}}
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;
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.
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!
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+/]*?,
Ruby 76 54 51 chars
x=gets.scan /\w+/;$><<x.dup.map{x.delete(x.min)}*?,
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)
SED, 135
s/.*/,&,!,abcdefghijklmnopqrstuvwxyz/;:;s/\(,\([^,]*\)\(.\)[^,]*\)\(.*\)\(,\2\(.\)[^,]*\)\(.*!.*\6.*\3\)/\5\1\4\7/;t;s/^,\(.*\),!.*/\1/
Based on my previous sorting entry
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=",")
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
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)
i am looking for a way to eliminate b.
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
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]