Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
(+Icon+Unicon) |
|||
Line 653:
ENDDO
END</lang>
=={{header|Icon}}==
While bubble sort is a basic algorithm it also illustrates a difference in the way Icon handles types. The built-in operators for comparing data types make a syntactic distinction between numeric and string types. Consequently, when writing something like a bubble sort you must (a) write two versions, (b) have the sort figure it out dynamically as in this example.
<lang Icon>procedure bubblesort(X,op) #: simple bubble sort
local i,sorted
op := case op of { # select how to sort
"<<"|">>"|"<<="|">>="|"<"|">"|"<="|">=": proc(op,2)
"string": proc("<<",2)
"numeric": proc("<",2)
&null: if type(X[1]) == "string" then proc("<<",2)
else proc("<",2)
default: runerr(123,op)
}
while /sorted := 1 do # the sort
every i := 2 to *X do
if op(X[i],X[i-1]) then {
X[i-1] :=: X[i]
sorted := &null
}
return X
end</lang>
This code will demonstrate the bubble sort using arguments supplied as arguments. The last sort call on a string rather than a list illustrates how many Icon operators work on different types. The example could be made more general to deal with coercion of types like cset to sting (admittedly an uninteresting example as csets are already sorted).
<pre>procedure main(l2) #: demo bubblesort
l1 := copy(l2) # list of strings
l2[1] := numeric(l2[1]) # force list with leading numeric
displaysort(copy(l1)) # default string sort
displaysort(copy(l2)) # default numeric sort
displaysort(copy(l2),"string") # explicit string sort
displaysort(copy(l1),"numeric") # explicit numeric sort
displaysort(copy(l2),"<<") # descending string sort
displaysort(copy(l2),"<") # descending numeric sort
displaysort("qwerty") # sort characters in a string
end
procedure displaysort(X,op) #: show bubblesort behavior
write("--- bubblesort ---")
write("op = ",image(op))
writex("before = ",X)
writex("after = ",bubblesort(X,op))
write()
return
end
procedure writex(tag,X) #: helper for displaysort
writes(\tag)
if type(X) == "string" then write(image(X))
else {
writes("[")
every writes(" ",image(!X))
write(" ]")
}
return
end</pre>
=={{header|J}}==
Line 1,494 ⟶ 1,553:
foo 10 bsort
foo 10 .array</lang>
=={{header|Unicon}}==
See [[#Icon|Icon]].
=={{header|UnixPipes}}==
<lang bash>rm -f _sortpass
|