Sunday, July 26, 2015

sort items by priority in array inplace

enum priority:
    high = 1,
    medium = 2,
    low = 3
This works for n priorities.
// sort asc by priority inplace asc
// assume priorities is sorted asc too
(a, priorities):
    if a == null || priorities == null:
        throw
    if a.length() == 0 || priorities.length() == 0:
        return
    //priorities.sort()
    start = 0, end = a.length()-1
    for p = 0, p < priorities.length()-1, p++: // skip last
        priority = priorities[p]
        while start < end:
            item = a[start]
            if item.priority() == priority:
                start++
            else:
                swap(a, start, end)
                end--
        end = a.length()-1
[Hat tip to ts]

No comments:

Post a Comment