Jump to content

Sorting algorithms/Tree sort on a linked list: Difference between revisions

julia example
(added Ol)
(julia example)
Line 185:
 
But task's the current url for Finnegan's Wake does not point at flat text and constructing such a thing would be a different task...
 
=={{header|Julia}}==
<lang julia>mutable struct BTree{T}
data::T
left::Union{BTree, Nothing}
right::Union{BTree, Nothing}
BTree(val::T) where T = new{T}(val, nothing, nothing)
end
 
function insert(tree, data)
if data < tree.data
if tree.left == nothing
tree.left = BTree(data)
else
insert(tree.left, data)
end
else
if tree.right == nothing
tree.right = BTree(data)
else
insert(tree.right, data)
end
end
end
 
function sorted(tree)
return tree == nothing ? [] :
typeof(tree.data)[sorted(tree.left); tree.data; sorted(tree.right)]
end
 
function arraytotree(arr)
tree = BTree(arr[1])
for data in arr[2:end]
insert(tree, data)
end
return tree
end
 
function testtreesort(arr)
println("Unsorted: ", arr)
tree = arraytotree(arr)
println("Sorted: ", sorted(tree))
end
 
testtreesort(rand(1:99, 12))
</lang>{{out}}
<pre>
Unsorted: [1, 12, 15, 22, 28, 26, 69, 22, 1, 62, 73, 95]
Sorted: [1, 1, 12, 15, 22, 22, 26, 28, 62, 69, 73, 95]
</pre>
 
=={{header|Kotlin}}==
4,105

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.