Anonymous user
Sorting algorithms/Bubble sort: Difference between revisions
→{{header|Icon}}
m (fix tags) |
|||
Line 654:
END</lang>
=={{header|Icon and Unicon}}==
==={{header|Icon}}===
While bubble sort is a basic algorithm it also illustrates a difference in the way Icon handles types. Built-in
operators for comparing data types make a syntactic distinction between numeric and string types, and sorting
structured and user-defined types requires custom code. The following code
allows the user to specify the type of comparison to use but handles integer
or string lists automatically.
<lang icon>invocable all
procedure bubblesort(X,op) #: simple bubble sort
local i,sorted
op := case op of { # select how to sort
"string": "<<"
"numeric": "<"
&null: if type(X[1]) == "string" then "<<" else "<"
default: op
}
op := proc(op, 2) | runerr(123, image(op))
while /sorted := "yes" 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 demonstrates 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 string
(admittedly an uninteresting example as csets are already sorted).
<lang icon>procedure main(l1) #: demo bubblesort
writes("Sorting : ")
writex(l1)
displaysort(copy(l1)) # default string sort
displaysort(copy(l1),"numeric") # explicit numeric sort
displaysort(copy(l1),"string") # explicit string sort
displaysort(copy(l1),"<<") # descending string sort
displaysort(copy(l1),"<") # descending numeric sort
displaysort(copy(l1),cmp) # ascending custom comparison
displaysort(copy(l1),"cmp") # ascending custom comparison
writex("qwerty")
displaysort(
end
procedure cmp(a,b)
return a > b # Imagine a complex comparsion test here!
end
procedure displaysort(X,op) #: show bubblesort behavior
writex(bubblesort(X,op))
end
procedure writex(
if type(X) == "string" then write(image(X))
else {
writes("[")
every writes("
end</lang>
Sample output:
<pre>-
Sorting : [ "3" "1" "4" "1" "5" "9" "2" "6" "3" ]
--- bubblesort with op = "string": [ "1" "1" "2" "3" "3" "4" "5" "6" "9" ]
--- bubblesort with op = "<<": [ "1" "1" "2" "3" "3" "4" "5" "6" "9" ]
--- bubblesort with op = "<": [ "1" "1" "2" "3" "3" "4" "5" "6" "9" ]
--- bubblesort with op = procedure cmp: [ "9" "6" "5" "4" "3" "3" "2" "1" "1" ]
--- bubblesort with op = "cmp": [ "9" "6" "5" "4" "3" "3" "2" "1" "1" ]
Sorting string: "qwerty"
--- bubblesort with op = &null: "eqrtwy"
-></pre>
==={{header|Unicon}}===
The Icon solution also works in Unicon.
=={{header|J}}==
|