
Sorting Algorithm

This is a sorting algorithm.   It may be applied to a set of data in order to sort it.    
For comparing various sorts, see compare sorts.  
For other sorting algorithms,   see sorting algorithms,   or:

O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort


Use the quickselect algorithm on the vector

 [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page.

 Note: Quicksort has a separate task. 


quick = cluster [T: type] is select
        where T has lt: proctype (T,T) returns (bool)
    aT = array[T]
    sT = sequence[T]
    rep = null
 
    swap = proc (list: aT, a, b: int)
        temp: T := list[a]
        list[a] := list[b]
        list[b] := temp
    end swap
 
    partition = proc (list: aT, left, right, pivotIndex: int) returns (int)
        pivotValue: T := list[pivotIndex]
        swap(list, pivotIndex, right)
        storeIndex: int := left
        for i: int in int$from_to(left, right-1) do
            if list[i] < pivotValue then
                swap(list, storeIndex, i)
                storeIndex := storeIndex + 1
            end
        end
        swap(list, right, storeIndex)
        return(storeIndex)
    end partition
 
    _select = proc (list: aT, left, right, k: int) returns (T)
        if left = right then
            return(list[left])
        end
 
        pivotIndex: int := left + (right - left + 1) / 2
        pivotIndex := partition(list, left, right, pivotIndex)
        if k = pivotIndex then
            return(list[k])
        elseif k < pivotIndex then
            return(_select(list, left, pivotIndex-1, k))
        else
            return(_select(list, pivotIndex + 1, right, k))
        end
    end _select
 
    select = proc (list: sT, k: int) returns (T)
        return(_select(sT$s2a(list), 1, sT$size(list), k))
    end select
end quick
 
start_up = proc ()
    po: stream := stream$primary_output()
    vec: sequence[int] := sequence[int]$[9,8,7,6,5,0,1,2,3,4]
 
    for k: int in int$from_to(1, 10) do
        item: int := quick[int]$select(vec, k)
        stream$putl(po, int$unparse(k) || ": " || int$unparse(item))
    end
end start_up