Rebol3 Code Examplex


Sorting algorithms/Shell sort

Sort elements by comparing and shifting items at decreasing gaps, then finish with a final insertion-sort pass.

Rebol [
    title: "Rosetta code: Sorting algorithms/Shell sort"
    file:  %Sorting_algorithms-Shell_sort.r3
    url:   https://rosettacode.org/wiki/Sorting_algorithms-Shell_sort
]

shell-sort: function [
    "Sorts a block in place using Shell sort algorithm"
    a [block!]
][
    n: length? a
    g: n >> 1                   ;; initial gap = half the length
    while [g > 0][
        i: g + 1
        while [n >= j: i][
            e: a/:i             ;; element to insert
            ;; shift elements right while they are larger than e
            while [all [j > g  e < a/(j - g)]][
                a/:j: a/(j - g)
                j: j - g
            ]
            a/:j: e             ;; place e in its sorted position
            ++ i
        ]
        g: g >> 1               ;; shrink gap
    ]
    a
]

random/seed 1
data: make block! max: 10000
loop max [append data random max]

time: delta-time [ shell-sort data ] 
print ["shell-sort time:" time]  
print ["sorted:^/" copy/part data 30 "^/...^/" skip tail data -16]

Output:

shell-sort time: 0:00:00.106153
sorted:
1 1 2 6 6 7 7 8 11 12 13 17 17 18 19 20 20 22 22 24 24 25 25 25 28 29 30 33 34 34 
...
9983 9984 9986 9987 9988 9988 9989 9991 9991 9995 9996 9997 9998 9999 10000 10000