*is a*

**Sorting algorithms/Tree sort on a linked list****draft**programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

**Sorting Algorithm**

This is a sorting algorithm. It may be applied to a set of data in order to sort it.

**O(**

*n*log*n*) SortsHeapsort | Mergesort | Quicksort

**O(**

*n*log^{2}*n*) SortsShell Sort

**O(**

*n*^{2}) SortsBubble sort | Cocktail sort | Comb sort | Gnome sort | Insertion sort | Selection sort | Strand sort

**Other Sorts**

Bead sort | Bogosort | Counting sort | Pancake sort | Permutation sort | Radix sort | Sleep sort | Stooge sort

**Please read the discussion page and NOT add to this task until the task itself is improved. (Or deleted).**

This page uses content from |

A **tree sort** is a sort algorithm that builds a binary search tree from the keys to be sorted, and then traverses the tree (in-order) so that the keys come out in sorted order. Its typical use is when sorting the elements of a stream from a file. Several other sorts would have to load the elements to a temporary data structure, whereas in a tree sort the act of loading the input into a data structure is sorting it.

The tree sort is considered by some to be the faster method to sort a linked list, followed by Quicksort and Mergesort:

Sediment sort, bubble sort, selection sort perform very badly.

**Test case:** Create a linked list of all the sentences of all the episodes of Finnegans Wake by James Joyce. Load them into a local memory based linked list, then tree sort them inplace and print the number of node swaps and seconds of BogoMips are necessary to perform the sort. (The book is to be stored locally (whole *or* in individual episodes) in a test text file on disk before loading by the specimin code into a linked list for sorting.)

## J[edit]

What *is* a sentence in Finnegan's Wake? Let's say that it's all the text leading up to a period, question mark or exclamation point if (and only if) the character is followed by a space or newline. (There are some practical difficulties here - this means, for example, that the first sentence of a chapter includes the chapter heading - but it's good enough for now.)

There's also the issue of how do we want to sort the sentences? Let's say we'll sort them in ascii order without normalization of the text (since that is simplest).

Let's also say that we have prepared a file which contains some sort of ascii rendition of the text. Note that the final result we get here will depend on exactly how that ascii rendition was prepared. But let's just ignore that issue so we can get something working.

Next, we need to think of what kind of tree, there are a great number of kinds of trees, and they can be categorized in many different ways. For example, a directory tree is almost never a balanced binary tree. (Note that a linked list is a kind of a tree - an extremely tall and skinny unbalanced tree, but a tree nonetheless - and a binary tree at that. Then again, note that efficiency claims in general are specious, because efficient for one purpose tends to be inefficient for many other purposes.) Since we are going for efficiency here, we will implement a short, fat tree (let's call that "efficient use of the programmer's time" or something like that...). Specifically, we'll be implementing a one level deep tree which happens to have 14961 leaves connected directly to the root node. (Edit: task description has been changed to mandate a specific binary tree. But we are going to ignore that here, since the consequence would be several orders of magnitude slowdown, and a lot of extra code to write. That kind of detail can be useful in an educational setting, and in some technology settings, but it would cause real problems here.)

Simplicity is a virtue, right?

Finally, there's the matter of counting swaps. Let's define our swap count as the minimal number of swaps which would be needed to produce our sorted result.

With these choices, the task becomes:

finn=: fread '~user/temp/wake/finneganswake.txt'

sentences=: (<;.2~ '. '&[email protected]&(LF,' !.?.')) finn

#sentences

14961

+/<:#@>C./:sentences

14945

We have to swap almost every sentence, but 16 of them can be sorted "for free" with the swaps of the other sentences.

For that matter, inspecting the lengths of the cycles formed by the minimal arrangements of swaps...

/:~ #@>C./:sentences

1 1 2 2 4 9 12 25 32 154 177 570 846 935 1314 10877

... we can see that two of the sentences were fine right where they start out. Let's see what they are:

;:inv (#~(= /:~))sentences

Very, all

fourlike tellt. What tyronte power!

So now you know.

(Processing time here is negligible - other than the time needed to fetch a copy of the book and render it as plain text ascii - but if we were careful to implement the efficiency recommendations of this task more in the spirit of whatever the task is presumably implying, we could probably increase the processing time by several orders of magnitude.)

So... ok... let's do this "right" (which is to say according to the current task specification, as opposed to the task specification that was present for the early drafts - though, perhaps, using Finnegan's Wake as a data set encourages a certain degree of ... informality?).

Anyways, here we go:

left=: i.0

right=: i.0

data=: i.0

insert=:3 :0"0

k=. 0

assert. (left =&# right) * (left =&# data)

if. 0<#data do.

while. k<#data do.

if. y=k{data do.return.end.

n=. k

if. y<k{data do.

k=. k{".p=.'left'

else.

k=. k{".p=.'right'

end.

end.

(p)=:(#data) n} ".p

end.

left=:left, _

right=:right, _

data=:data,y

i.0 0

)

flatten=:3 :0

extract 0

)

extract=:3 :0

if. y>:#data do.'' return. end.

(extract y{left),(y{data),extract y{right

)

This could be wrapped differently, but it's adequate for this task.

Example use would be something like:

insert sentences

extract''

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...

## Kotlin[edit]

As I can't be bothered to download Finnegan's Wake and deal with the ensuing uncertainties, I've contented myself by following a similar approach to the Racket and Scheme entries:

// version 1.1.51

import java.util.LinkedList

class BinaryTree<T : Comparable<T>> {

var node: T? = null

lateinit var leftSubTree: BinaryTree<T>

lateinit var rightSubTree: BinaryTree<T>

fun insert(item: T) {

if (node == null) {

node = item

leftSubTree = BinaryTree<T>()

rightSubTree = BinaryTree<T>()

}

else if (item < node as T) {

leftSubTree.insert(item)

}

else {

rightSubTree.insert(item)

}

}

fun inOrder() {

if (node == null) return

leftSubTree.inOrder()

print("$node ")

rightSubTree.inOrder()

}

}

fun <T : Comparable<T>> LinkedList<T>.treeSort() {

val searchTree = BinaryTree<T>()

for (item in this) searchTree.insert(item)

print("${this.joinToString(" ")} -> ")

searchTree.inOrder()

println()

}

fun main(args: Array<String>) {

val ll = LinkedList(listOf(5, 3, 7, 9, 1))

ll.treeSort()

val ll2 = LinkedList(listOf('d', 'c', 'e', 'b' , 'a'))

ll2.treeSort()

}

- Output:

5 3 7 9 1 -> 1 3 5 7 9 d c e b a -> a b c d e

## Racket[edit]

-- this implementation illustrates differences in identifiers and syntaxes of Scheme and Racket's`match-lambda`

family. `racket/match`

documented here.
#lang racket/base

(require racket/match)

(define insert

;; (insert key tree)

(match-lambda**

[(x '()) `(() ,x ())]

[(x '(() () ())) `(() ,x ())]

[(x `(,l ,k ,r)) #:when (<= x k) `(,(insert x l) ,k ,r)]

[(x `(,l ,k ,r)) `(,l ,k ,(insert x r))]

[(_ _) "incorrect arguments or broken tree"]))

(define in-order

;; (in-order tree)

(match-lambda

[`(() ,x ()) `(,x)]

[`(,l ,x ()) (append (in-order l) `(,x))]

[`(() ,x ,r) (append `(,x) (in-order r))]

[`(,l ,x ,r) (append (in-order l) `(,x) (in-order r))]

[_ "incorrect arguments or broken tree"]))

(define (tree-sort lst)

(define tree-sort-itr

(match-lambda**

[(x `()) (in-order x)]

[(x `(,a . ,b)) (tree-sort-itr (insert a x) b)]

[(_ _) "incorrect arguments or broken tree"]))

(tree-sort-itr '(() () ()) lst))

(tree-sort '(5 3 7 9 1))

- Output:

'(1 3 5 7 9)

## Scheme[edit]

The following implements a sorting algorithm that takes a linked list, puts each key into an unbalanced binary tree and returns an in-order traversal of the tree.

(use matchable)Usage:

(define insert

;; (insert key tree)

(match-lambda*

[(x ()) `(() ,x ()) ]

[(x (() () ())) `(() ,x ()) ]

[(x (l k r))

(=> continue)

(if (<= x k)

`(,(insert x l) ,k ,r)

(continue)) ]

[(x (l k r)) `(,l ,k ,(insert x r)) ]

[_ "incorrect arguments or broken tree" ]))

(define in-order

;; (in-order tree)

(match-lambda

[(() x ()) `(,x)]

[(l x ()) (append (in-order l) `(,x))]

[(() x r) (append `(,x) (in-order r))]

[(l x r) (append (in-order l) `(,x) (in-order r))]

[_ "incorrect arguments or broken tree" ]))

(define (tree-sort lst)

(define tree-sort-itr

(match-lambda*

[(x ()) (in-order x)]

[(x (a . b)) (tree-sort-itr (insert a x) b)]

[_ "incorrect arguments or broken tree" ]))

(tree-sort-itr '(() () ()) lst))

#;2> (tree-sort '(5 3 7 9 1))

(1 3 5 7 9)

## zkl[edit]

This code reads a file [of source code] line by line, and builds a binary tree of the first word of each line. Then prints the sorted list.

class Node{

var left,right,value;

fcn init(value){ self.value=value; }

}

class Tree{

var root;

fcn add(value){

if(not root){ root=Node(value); return(self); }

fcn(node,value){

if(not node) return(Node(value));

if(value!=node.value){ // don't add duplicate values

if(value<node.value) node.left =self.fcn(node.left, value);

else node.right=self.fcn(node.right,value);

}

node

}(root,value);

return(self);

}

fcn walker{ Utils.Generator(walk,root); }

fcn walk(node){ // in order traversal

if(node){

self.fcn(node.left);

vm.yield(node.value);

self.fcn(node.right);

}

}

}

tree:=Tree();

File("bbb.zkl").pump(tree.add,fcn(line){ // 5,000 lines to 660 words

line.split(" ")[0].strip(); // take first word

});

foreach word in (tree){ println(word) }

- Output:

... Atomic.sleep(0.5); Atomic.sleep(100000); Atomic.sleep(2); Atomic.waitFor(fcn{ Boyz:=Boys.pump(D(),fcn([(b,gs)]){ Compiler.Compiler.compileText(code)(); ...