Programming Search⌘K

Taskcore

Use a priority queue

Also called heap queue, max-heap, min-heap, pop the largest, serve by priority, custom priority order.

Serve requests by priority with the standard priority queue of each tier 1 language, with a custom order, a max-heap and ties in arrival order.

Task

Use a priority queue to serve requests by priority. The function serve_order(priorities) gets a list: request i has the priority priorities[i]. It pushes each request onto a priority queue, then pops the requests one at a time. A larger priority comes out first. Requests with equal priorities come out in arrival order, so the smaller request number comes first. The function returns the request numbers in that order.

For example, serve_order([2, 5, 1, 5]) is [1, 3, 0, 2]. Requests 1 and 3 have the priority 5, and request 1 arrived first. Each priority fits in a signed 32-bit integer. For the idea, see Priority queue. For how a binary heap works, see binary heap on the algorithms site.

Three details make this task harder than a call to push and pop:

  • The largest priority must come out first, but some standard types put the smallest first.
  • Most heaps do not keep the arrival order of equal priorities.
  • A comparison that subtracts two 32-bit priorities can overflow.

Solutions

Language Priority queue How the largest comes first, with ties in arrival order
Python heapq on a list push (-p, i)
JavaScript a small binary heap class before(a, b) compares p[a] > p[b], then a < b
TypeScript a small generic Heap<T> class the same before function
Java PriorityQueue<Integer> comparingInt(priorities::get).reversed().thenComparingInt(i -> i)
C a binary heap in an array before compares with > and ==
C++ std::priority_queue a lambda that returns true if a comes out after b
C# PriorityQueue<int, (int, int)> an IComparer made with Comparer.Create
Go container/heap Less on a type that implements heap.Interface
Rust BinaryHeap<(i32, Reverse<usize>)> a max-heap; Reverse(i) for the ties
Bash no priority queue; sort sort -k1,1nr -k2,2n
  • Python heapq is a min-heap. "heap[0] is the smallest item"1. The solution pushes the tuple (-p, i), so the largest priority is the smallest tuple. The request number i is the tie-breaker. The documentation gives the same method: "The entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added."1 Python 3.14 and later also have heappush_max and heappop_max for a max-heap: "Added in version 3.14."1 The solution uses -p, so it also runs on older versions.
  • Java needs a comparator for a max-heap. "The head of this queue is the least element with respect to the specified ordering."2 The comparator makes the largest priority the least. For equal elements, "ties are broken arbitrarily"2, so the comparator also compares the request numbers.
  • C++ has a max-heap with a reversed comparator. By default, the queue gives "constant time lookup of the largest (by default) element"3. The comparator is a "less than": "Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering."3 So the lambda returns true if a comes out after b.
  • C# has a min-heap with no arrival order. "Elements with the lowest priority are dequeued first."4 Also, "Note that the type does not guarantee first-in-first-out semantics for elements of equal priority."4 The solution uses the pair (priority, index) as the priority and a comparer that puts the largest priority first.
  • Go gives heap functions, not a heap type. "Package heap provides heap operations for any type that implements heap.Interface."5 The type gives Len, Less, Swap, Push and Pop, and Less decides the order.
  • Rust BinaryHeap is a max-heap. "A priority queue implemented with a binary heap. This will be a max-heap."6 Tuples compare item by item. (p, Reverse(i)) puts the largest priority first, and Reverse makes the smaller request number the larger value. For a min-heap, "Either core::cmp::Reverse or a custom Ord implementation can be used to make BinaryHeap a min-heap."6
  • JavaScript, TypeScript and C have no priority queue. The solutions contain a small binary heap with a before function. push moves the new item up, and pop moves the last item from the root down.
  • Bash uses sort. In this task, all of the requests come before the first one is served, so a sort gives the same order as a priority queue. -k1,1nr sorts the priorities as numbers, largest first, and -k2,2n sorts equal priorities by request number. A program that adds requests while it serves others needs a real priority queue.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: no requests give an empty list.
  • one: one request gives [0].
  • ties: four equal priorities come out in the order 0, 1, 2, 3. A heap with no tie-breaker can give another order.
  • negative: all priorities are below 0, and -1 is the largest.
  • int32-extremes: the smallest and the largest 32-bit integers are in the list. A comparator that computes b - a overflows here. Negation also fails: in Java, "negation of the maximum negative int or long results in that same maximum negative number."7 The Python solution negates with no overflow.
  • sorted and reversed: the order of the input does not change the rule.

Pitfalls

  • Python heapq pops the smallest item. If you push the priorities, the smallest priority comes out first. Push -p for the largest first:
import heapq

heap = []
for p in [2, 5, 1]:
    heapq.heappush(heap, p)
print("pushed p, popped", heapq.heappop(heap))

heap = []
for p in [2, 5, 1]:
    heapq.heappush(heap, -p)
print("pushed -p, popped", -heapq.heappop(heap))
Output
pushed p, popped 1
pushed -p, popped 5
  • Java (a, b) -> b - a overflows. "If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format."7 And "a-b produces the same result as a+(-b)"7. So for large priorities, b - a gives the wrong sign, and the queue gives the wrong head. Use Integer.compare(b, a):
import java.util.PriorityQueue;

public class Main {
  public static void main(String[] args) {
    PriorityQueue<Integer> subtract = new PriorityQueue<>((a, b) -> b - a);
    PriorityQueue<Integer> compare = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
    for (int p : new int[] {Integer.MIN_VALUE, 1, Integer.MAX_VALUE}) {
      subtract.offer(p);
      compare.offer(p);
    }
    System.out.println("b - a: " + subtract.poll());
    System.out.println("Integer.compare(b, a): " + compare.poll());
  }
}
Output
b - a: -2147483648
Integer.compare(b, a): 2147483647
  • C++ std::greater gives the smallest on top. The documentation says that "using std::greater would cause the smallest element to appear as the top()"3. This is the opposite of what the name seems to say:
#include <functional>
#include <iostream>
#include <queue>
#include <vector>

int main() {
    std::priority_queue<int> by_less;
    std::priority_queue<int, std::vector<int>, std::greater<int>> by_greater;
    for (int p : {2, 5, 1}) {
        by_less.push(p);
        by_greater.push(p);
    }
    std::cout << "std::less (the default), top: " << by_less.top() << '\n';
    std::cout << "std::greater, top: " << by_greater.top() << '\n';
}
Output
std::less (the default), top: 5
std::greater, top: 1
  • C# equal priorities do not come out in arrival order. The type "does not guarantee first-in-first-out semantics for elements of equal priority."4 Here, five items with the same priority come out in another order. Add the arrival number to the priority, as the solution does:
using System;
using System.Collections.Generic;

var queue = new PriorityQueue<string, int>();
foreach (string name in new[] { "A", "B", "C", "D", "E" })
{
    queue.Enqueue(name, 0);
}
var order = new List<string>();
while (queue.TryDequeue(out var item, out _))
{
    order.Add(item);
}
Console.WriteLine(string.Join(" ", order));
Output
A E D C B
  • Go: call heap.Push, not the Push method. "Note that Push and Pop in this interface are for package heap's implementation to call. To add and remove things from the heap, use heap.Push and heap.Pop."5 The method only appends, so the heap is then not in order:
package main

import (
	"container/heap"
	"fmt"
)

type ints []int

func (h ints) Len() int           { return len(h) }
func (h ints) Less(i, j int) bool { return h[i] < h[j] }
func (h ints) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *ints) Push(x any)        { *h = append(*h, x.(int)) }
func (h *ints) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

func main() {
	a := &ints{5, 2, 8}
	heap.Init(a)
	a.Push(1)
	fmt.Println("after a.Push(1), smallest out:", heap.Pop(a))

	b := &ints{5, 2, 8}
	heap.Init(b)
	heap.Push(b, 1)
	fmt.Println("after heap.Push(b, 1), smallest out:", heap.Pop(b))
}
Output
after a.Push(1), smallest out: 2
after heap.Push(b, 1), smallest out: 1
  • Bash sort without -n compares text. -n is "compare according to string numerical value"8. Without it, 9 comes after 10, because the character 9 comes after the character 1:
printf '%s\n' 9 10 -2 | sort -r | head -n 1
printf '%s\n' 9 10 -2 | sort -nr | head -n 1
Output
9
10

Code

The build runs the native tests of each language in a pinned toolchain.

serve_order.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-priority-queue/.

import heapq


def serve_order(priorities: list[int]) -> list[int]:
    """Returns the request numbers in serve order: the largest priority
    first, and for equal priorities, the smaller request number first."""
    heap: list[tuple[int, int]] = []
    for i, p in enumerate(priorities):
        # heapq is a min-heap, so -p puts the largest priority on top. The
        # request number i breaks ties and keeps the arrival order.
        heapq.heappush(heap, (-p, i))
    return [heapq.heappop(heap)[1] for _ in range(len(heap))]
test_serve_order.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-priority-queue/.

import pytest

from serve_order import serve_order

LO, HI = -2147483648, 2147483647

CASES = {
    "example": ([2, 5, 1, 5], [1, 3, 0, 2]),
    "longer": ([3, 1, 4, 1, 5, 9, 2, 6], [5, 7, 4, 2, 0, 6, 1, 3]),
    "empty": ([], []),
    "one": ([7], [0]),
    "ties": ([4, 4, 4, 4], [0, 1, 2, 3]),
    "negative": ([-3, -1, -2], [1, 2, 0]),
    "int32-extremes": ([LO, HI, 0, LO], [1, 2, 0, 3]),
    "sorted": ([1, 2, 3], [2, 1, 0]),
    "reversed": ([3, 2, 1], [0, 1, 2]),
}


@pytest.mark.parametrize("case", CASES)
def test_serve_order(case):
    priorities, want = CASES[case]
    before = list(priorities)
    assert serve_order(priorities) == want
    assert priorities == before
serve_order.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

#include "serve_order.hpp"

#include <queue>

std::vector<std::size_t> serve_order(const std::vector<std::int32_t> &priorities) {
    // std::priority_queue puts the largest element for its comparator on
    // top. The comparator is a "less than": a is less than b if a comes out
    // after b.
    auto after = [&priorities](std::size_t a, std::size_t b) {
        if (priorities[a] != priorities[b]) {
            return priorities[a] < priorities[b];
        }
        return a > b;
    };
    std::priority_queue<std::size_t, std::vector<std::size_t>, decltype(after)> queue(after);
    for (std::size_t i = 0; i < priorities.size(); i++) {
        queue.push(i);
    }
    std::vector<std::size_t> served;
    while (!queue.empty()) {
        served.push_back(queue.top()); // read top() first:
        queue.pop();                   // pop() returns nothing
    }
    return served;
}
serve_order.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

#pragma once

#include <cstddef>
#include <cstdint>
#include <vector>

// serve_order returns the request numbers in serve order: the largest
// priority first, and for equal priorities, the smaller request number first.
std::vector<std::size_t> serve_order(const std::vector<std::int32_t> &priorities);
test_serve_order.cpp 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

#include "serve_order.hpp"

#include <cstddef>
#include <cstdint>
#include <iostream>
#include <limits>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view label, const std::vector<std::int32_t> &priorities,
                  const std::vector<std::size_t> &want) {
    if (serve_order(priorities) != want) {
        std::cerr << "case " << label << " failed\n";
        failures++;
    }
}

int main() {
    constexpr auto hi = std::numeric_limits<std::int32_t>::max();
    constexpr auto lo = std::numeric_limits<std::int32_t>::min();
    check("example", {2, 5, 1, 5}, {1, 3, 0, 2});
    check("longer", {3, 1, 4, 1, 5, 9, 2, 6}, {5, 7, 4, 2, 0, 6, 1, 3});
    check("empty", {}, {});
    check("one", {7}, {0});
    check("ties", {4, 4, 4, 4}, {0, 1, 2, 3});
    check("negative", {-3, -1, -2}, {1, 2, 0});
    check("int32-extremes", {lo, hi, 0, lo}, {1, 2, 0, 3});
    check("sorted", {1, 2, 3}, {2, 1, 0});
    check("reversed", {3, 2, 1}, {0, 1, 2});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
ServeOrder.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

final class ServeOrder {
  private ServeOrder() {}

  /**
   * Returns the request numbers in serve order: the largest priority first, and for equal
   * priorities, the smaller request number first.
   */
  static List<Integer> serveOrder(List<Integer> priorities) {
    // The head of a PriorityQueue is the least element for its comparator.
    // This comparator makes the largest priority the least, and for equal
    // priorities, the smaller request number.
    Comparator<Integer> order =
        Comparator.<Integer>comparingInt(priorities::get)
            .reversed()
            .thenComparingInt(i -> i);
    PriorityQueue<Integer> queue = new PriorityQueue<>(order);
    for (int i = 0; i < priorities.size(); i++) {
      queue.offer(i);
    }
    List<Integer> served = new ArrayList<>();
    while (!queue.isEmpty()) {
      served.add(queue.poll());
    }
    return served;
  }
}
ServeOrderTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ServeOrderTest {
  static Stream<Arguments> cases() {
    int lo = Integer.MIN_VALUE;
    int hi = Integer.MAX_VALUE;
    return Stream.of(
        Arguments.of("example", List.of(2, 5, 1, 5), List.of(1, 3, 0, 2)),
        Arguments.of("longer", List.of(3, 1, 4, 1, 5, 9, 2, 6), List.of(5, 7, 4, 2, 0, 6, 1, 3)),
        Arguments.of("empty", List.of(), List.of()),
        Arguments.of("one", List.of(7), List.of(0)),
        Arguments.of("ties", List.of(4, 4, 4, 4), List.of(0, 1, 2, 3)),
        Arguments.of("negative", List.of(-3, -1, -2), List.of(1, 2, 0)),
        Arguments.of("int32-extremes", List.of(lo, hi, 0, lo), List.of(1, 2, 0, 3)),
        Arguments.of("sorted", List.of(1, 2, 3), List.of(2, 1, 0)),
        Arguments.of("reversed", List.of(3, 2, 1), List.of(0, 1, 2)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void serveOrder(String name, List<Integer> priorities, List<Integer> want) {
    List<Integer> before = new ArrayList<>(priorities);
    assertEquals(want, ServeOrder.serveOrder(priorities));
    assertEquals(before, priorities);
  }
}
serve_order.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

#include "serve_order.h"

#include <stdlib.h>

// C has no priority queue type. This is a binary heap of request numbers in
// an array: the children of slot i are the slots 2i+1 and 2i+2.
struct heap {
    const int32_t *priority;
    size_t *items;
    size_t count;
};

// before is true if request a comes out before request b. It compares the
// priorities with < and ==, not with a subtraction that can overflow.
static bool before(const struct heap *h, size_t a, size_t b) {
    if (h->priority[a] != h->priority[b]) {
        return h->priority[a] > h->priority[b];
    }
    return a < b;
}

static void swap(size_t *x, size_t *y) {
    size_t t = *x;
    *x = *y;
    *y = t;
}

static void push(struct heap *h, size_t request) {
    size_t i = h->count++;
    h->items[i] = request;
    while (i > 0) {
        size_t parent = (i - 1) / 2;
        if (!before(h, h->items[i], h->items[parent])) {
            break;
        }
        swap(&h->items[i], &h->items[parent]);
        i = parent;
    }
}

static size_t pop(struct heap *h) {
    size_t top = h->items[0];
    h->items[0] = h->items[--h->count];
    size_t i = 0;
    for (;;) {
        size_t l = 2 * i + 1;
        size_t r = l + 1;
        size_t best = i;
        if (l < h->count && before(h, h->items[l], h->items[best])) {
            best = l;
        }
        if (r < h->count && before(h, h->items[r], h->items[best])) {
            best = r;
        }
        if (best == i) {
            return top;
        }
        swap(&h->items[i], &h->items[best]);
        i = best;
    }
}

bool serve_order(const int32_t *priorities, size_t n, size_t *order) {
    if (n == 0) {
        return true;
    }
    struct heap h = {priorities, malloc(n * sizeof(size_t)), 0};
    if (h.items == NULL) {
        return false;
    }
    for (size_t i = 0; i < n; i++) {
        push(&h, i);
    }
    for (size_t i = 0; i < n; i++) {
        order[i] = pop(&h);
    }
    free(h.items);
    return true;
}
serve_order.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

#ifndef SERVE_ORDER_H
#define SERVE_ORDER_H

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

// serve_order writes the n request numbers to order in serve order: the
// largest priority first, and for equal priorities, the smaller request
// number first. order must have room for n values. It returns false if it
// cannot get memory.
bool serve_order(const int32_t *priorities, size_t n, size_t *order);

#endif
test_serve_order.c 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

#include "serve_order.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

#define CHECK(label, p, want)                                                  \
    do {                                                                       \
        const int32_t priorities[] = p;                                        \
        const size_t expect[] = want;                                          \
        const size_t n = sizeof priorities / sizeof priorities[0];             \
        size_t order[sizeof priorities / sizeof priorities[0]] = {0};          \
        if (!serve_order(priorities, n, order) ||                              \
            memcmp(order, expect, sizeof expect) != 0) {                       \
            fprintf(stderr, "case %s failed\n", label);                        \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("example", L(2, 5, 1, 5), L(1, 3, 0, 2));
    CHECK("longer", L(3, 1, 4, 1, 5, 9, 2, 6), L(5, 7, 4, 2, 0, 6, 1, 3));
    size_t none[1] = {0};
    if (!serve_order(NULL, 0, none)) { // the case "empty"
        fprintf(stderr, "case empty failed\n");
        failures++;
    }
    CHECK("one", L(7), L(0));
    CHECK("ties", L(4, 4, 4, 4), L(0, 1, 2, 3));
    CHECK("negative", L(-3, -1, -2), L(1, 2, 0));
    CHECK("int32-extremes", L(INT32_MIN, INT32_MAX, 0, INT32_MIN), L(1, 2, 0, 3));
    CHECK("sorted", L(1, 2, 3), L(2, 1, 0));
    CHECK("reversed", L(3, 2, 1), L(0, 1, 2));
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
ServeOrder.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

using System.Collections.Generic;

public static class ServeOrder
{
    // PriorityQueue is a min-heap, and it does not keep the arrival order of
    // equal priorities. The comparer puts the largest priority first and
    // breaks ties with the request number.
    private static readonly IComparer<(int Priority, int Index)> Order =
        Comparer<(int Priority, int Index)>.Create((x, y) =>
            x.Priority != y.Priority ? y.Priority.CompareTo(x.Priority) : x.Index.CompareTo(y.Index));

    // Returns the request numbers in serve order.
    public static List<int> Of(IReadOnlyList<int> priorities)
    {
        var queue = new PriorityQueue<int, (int Priority, int Index)>(Order);
        for (int i = 0; i < priorities.Count; i++)
        {
            queue.Enqueue(i, (priorities[i], i));
        }
        var served = new List<int>();
        while (queue.TryDequeue(out int request, out _))
        {
            served.Add(request);
        }
        return served;
    }
}
ServeOrderTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

using System.Linq;
using Xunit;

public sealed class ServeOrderTests
{
    public static TheoryData<string, int[], int[]> Cases => new()
    {
        { "example", new[] { 2, 5, 1, 5 }, new[] { 1, 3, 0, 2 } },
        { "longer", new[] { 3, 1, 4, 1, 5, 9, 2, 6 }, new[] { 5, 7, 4, 2, 0, 6, 1, 3 } },
        { "empty", new int[0], new int[0] },
        { "one", new[] { 7 }, new[] { 0 } },
        { "ties", new[] { 4, 4, 4, 4 }, new[] { 0, 1, 2, 3 } },
        { "negative", new[] { -3, -1, -2 }, new[] { 1, 2, 0 } },
        { "int32-extremes", new[] { int.MinValue, int.MaxValue, 0, int.MinValue }, new[] { 1, 2, 0, 3 } },
        { "sorted", new[] { 1, 2, 3 }, new[] { 2, 1, 0 } },
        { "reversed", new[] { 3, 2, 1 }, new[] { 0, 1, 2 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] priorities, int[] want)
    {
        Assert.NotNull(name);
        var before = priorities.ToArray();
        Assert.Equal(want, ServeOrder.Of(priorities));
        Assert.Equal(before, priorities);
    }
}
serve_order.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

// JavaScript has no priority queue type. Heap is a small binary heap: the
// item for which before(a, b) is true comes out first.
class Heap {
  constructor(before) {
    this.before = before;
    this.items = [];
  }

  get size() {
    return this.items.length;
  }

  push(x) {
    const a = this.items;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (!this.before(a[i], a[parent])) break;
      [a[i], a[parent]] = [a[parent], a[i]];
      i = parent;
    }
  }

  pop() {
    const a = this.items;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let best = i;
        if (l < a.length && this.before(a[l], a[best])) best = l;
        if (r < a.length && this.before(a[r], a[best])) best = r;
        if (best === i) break;
        [a[i], a[best]] = [a[best], a[i]];
        i = best;
      }
    }
    return top;
  }
}

// serveOrder returns the request numbers in serve order: the largest
// priority first, and for equal priorities, the smaller request number first.
export function serveOrder(priorities) {
  const heap = new Heap(
    (a, b) => priorities[a] > priorities[b] || (priorities[a] === priorities[b] && a < b),
  );
  priorities.forEach((_, i) => heap.push(i));
  const order = [];
  while (heap.size > 0) order.push(heap.pop());
  return order;
}
serve_order.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { serveOrder } from "./serve_order.js";

const LO = -2147483648;
const HI = 2147483647;

const cases = [
  ["example", [2, 5, 1, 5], [1, 3, 0, 2]],
  ["longer", [3, 1, 4, 1, 5, 9, 2, 6], [5, 7, 4, 2, 0, 6, 1, 3]],
  ["empty", [], []],
  ["one", [7], [0]],
  ["ties", [4, 4, 4, 4], [0, 1, 2, 3]],
  ["negative", [-3, -1, -2], [1, 2, 0]],
  ["int32-extremes", [LO, HI, 0, LO], [1, 2, 0, 3]],
  ["sorted", [1, 2, 3], [2, 1, 0]],
  ["reversed", [3, 2, 1], [0, 1, 2]],
];

for (const [name, priorities, want] of cases) {
  test(name, () => {
    const before = [...priorities];
    assert.deepEqual(serveOrder(priorities), want);
    assert.deepEqual(priorities, before);
  });
}
serve_order.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

// TypeScript has no priority queue type. Heap is a small binary heap: the
// item for which before(a, b) is true comes out first.
class Heap<T> {
  private readonly items: T[] = [];
  private readonly before: (a: T, b: T) => boolean;

  constructor(before: (a: T, b: T) => boolean) {
    this.before = before;
  }

  get size(): number {
    return this.items.length;
  }

  push(x: T): void {
    const a = this.items;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (!this.before(a[i], a[parent])) break;
      [a[i], a[parent]] = [a[parent], a[i]];
      i = parent;
    }
  }

  pop(): T | undefined {
    const a = this.items;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0 && last !== undefined) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let best = i;
        if (l < a.length && this.before(a[l], a[best])) best = l;
        if (r < a.length && this.before(a[r], a[best])) best = r;
        if (best === i) break;
        [a[i], a[best]] = [a[best], a[i]];
        i = best;
      }
    }
    return top;
  }
}

// serveOrder returns the request numbers in serve order: the largest
// priority first, and for equal priorities, the smaller request number first.
export function serveOrder(priorities: readonly number[]): number[] {
  const heap = new Heap<number>(
    (a, b) => priorities[a] > priorities[b] || (priorities[a] === priorities[b] && a < b),
  );
  priorities.forEach((_, i) => heap.push(i));
  const order: number[] = [];
  for (let i = heap.pop(); i !== undefined; i = heap.pop()) order.push(i);
  return order;
}
serve_order.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { serveOrder } from "./serve_order.ts";

const LO = -2147483648;
const HI = 2147483647;

const cases: [string, number[], number[]][] = [
  ["example", [2, 5, 1, 5], [1, 3, 0, 2]],
  ["longer", [3, 1, 4, 1, 5, 9, 2, 6], [5, 7, 4, 2, 0, 6, 1, 3]],
  ["empty", [], []],
  ["one", [7], [0]],
  ["ties", [4, 4, 4, 4], [0, 1, 2, 3]],
  ["negative", [-3, -1, -2], [1, 2, 0]],
  ["int32-extremes", [LO, HI, 0, LO], [1, 2, 0, 3]],
  ["sorted", [1, 2, 3], [2, 1, 0]],
  ["reversed", [3, 2, 1], [0, 1, 2]],
];

for (const [name, priorities, want] of cases) {
  test(name, () => {
    const before = [...priorities];
    assert.deepEqual(serveOrder(priorities), want);
    assert.deepEqual(priorities, before);
  });
}
serve_order.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

// Package serveorder serves requests by priority with container/heap.
package serveorder

import "container/heap"

// requests is a heap of request numbers. It implements heap.Interface: the
// request for which Less is true comes out first.
type requests struct {
	priority []int32
	items    []int
}

func (r *requests) Len() int { return len(r.items) }

func (r *requests) Less(i, j int) bool {
	a, b := r.items[i], r.items[j]
	if r.priority[a] != r.priority[b] {
		return r.priority[a] > r.priority[b] // the largest priority first
	}
	return a < b // equal priorities: the arrival order
}

func (r *requests) Swap(i, j int) { r.items[i], r.items[j] = r.items[j], r.items[i] }

func (r *requests) Push(x any) { r.items = append(r.items, x.(int)) }

func (r *requests) Pop() any {
	n := len(r.items)
	x := r.items[n-1]
	r.items = r.items[:n-1]
	return x
}

// ServeOrder returns the request numbers in serve order: the largest
// priority first, and for equal priorities, the smaller request number first.
func ServeOrder(priorities []int32) []int {
	r := &requests{priority: priorities}
	for i := range priorities {
		heap.Push(r, i) // call heap.Push, not r.Push
	}
	served := []int{}
	for r.Len() > 0 {
		served = append(served, heap.Pop(r).(int))
	}
	return served
}
serve_order_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

package serveorder

import (
	"math"
	"slices"
	"testing"
)

var cases = []struct {
	name       string
	priorities []int32
	want       []int
}{
	{"example", []int32{2, 5, 1, 5}, []int{1, 3, 0, 2}},
	{"longer", []int32{3, 1, 4, 1, 5, 9, 2, 6}, []int{5, 7, 4, 2, 0, 6, 1, 3}},
	{"empty", []int32{}, []int{}},
	{"one", []int32{7}, []int{0}},
	{"ties", []int32{4, 4, 4, 4}, []int{0, 1, 2, 3}},
	{"negative", []int32{-3, -1, -2}, []int{1, 2, 0}},
	{"int32-extremes", []int32{math.MinInt32, math.MaxInt32, 0, math.MinInt32}, []int{1, 2, 0, 3}},
	{"sorted", []int32{1, 2, 3}, []int{2, 1, 0}},
	{"reversed", []int32{3, 2, 1}, []int{0, 1, 2}},
}

func TestServeOrder(t *testing.T) {
	for _, c := range cases {
		before := slices.Clone(c.priorities)
		if got := ServeOrder(c.priorities); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
		if !slices.Equal(c.priorities, before) {
			t.Errorf("%s: the input changed", c.name)
		}
	}
}
serve_order.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

use std::cmp::Reverse;
use std::collections::BinaryHeap;

/// Returns the request numbers in serve order: the largest priority first,
/// and for equal priorities, the smaller request number first.
pub fn serve_order(priorities: &[i32]) -> Vec<usize> {
    // BinaryHeap is a max-heap. Tuples compare item by item, so the largest
    // priority comes first. Reverse(i) makes the smaller request number the
    // larger value, so equal priorities keep the arrival order.
    let mut heap: BinaryHeap<(i32, Reverse<usize>)> = BinaryHeap::new();
    for (i, &p) in priorities.iter().enumerate() {
        heap.push((p, Reverse(i)));
    }
    let mut served = Vec::with_capacity(heap.len());
    while let Some((_, Reverse(i))) = heap.pop() {
        served.push(i);
    }
    served
}
tests/serve_order_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-priority-queue/.

use algo_use_a_priority_queue::serve_order;

#[test]
fn cases() {
    let (lo, hi) = (i32::MIN, i32::MAX);
    let cases: Vec<(&str, Vec<i32>, Vec<usize>)> = vec![
        ("example", vec![2, 5, 1, 5], vec![1, 3, 0, 2]),
        ("longer", vec![3, 1, 4, 1, 5, 9, 2, 6], vec![5, 7, 4, 2, 0, 6, 1, 3]),
        ("empty", vec![], vec![]),
        ("one", vec![7], vec![0]),
        ("ties", vec![4, 4, 4, 4], vec![0, 1, 2, 3]),
        ("negative", vec![-3, -1, -2], vec![1, 2, 0]),
        ("int32-extremes", vec![lo, hi, 0, lo], vec![1, 2, 0, 3]),
        ("sorted", vec![1, 2, 3], vec![2, 1, 0]),
        ("reversed", vec![3, 2, 1], vec![0, 1, 2]),
    ];
    for (name, priorities, want) in cases {
        assert_eq!(serve_order(&priorities), want, "case {name}");
    }
}
serve_order.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-priority-queue/.

# serve_order PRIORITY...
# Prints the request numbers in serve order on one line: the largest priority
# first, and for equal priorities, the smaller request number first. Bash has
# no priority queue. When all of the requests come before the first one is
# served, a sort gives the same order: sort -n compares the priorities as
# numbers, -r makes the largest first, and the second key keeps the arrival
# order of equal priorities.
serve_order() {
  local i
  local -a order=()
  mapfile -t order < <(
    for ((i = 1; i <= $#; i++)); do
      printf '%s %s\n' "${!i}" "$((i - 1))"
    done | sort -k1,1nr -k2,2n | cut -d ' ' -f 2
  )
  printf '%s\n' "${order[*]}"
}
test_serve_order.bats 27 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-priority-queue/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/serve_order.sh"
}

check() { # check WANT PRIORITY...
  local want=$1
  shift
  run serve_order "$@"
  [ "$status" -eq 0 ]
  [ "$output" = "$want" ] || { printf 'got:  %s\nwant: %s\n' "$output" "$want"; return 1; }
}

@test "example" { check '1 3 0 2' 2 5 1 5; }
@test "longer" { check '5 7 4 2 0 6 1 3' 3 1 4 1 5 9 2 6; }
@test "empty" { check ''; }
@test "one" { check '0' 7; }
@test "ties" { check '0 1 2 3' 4 4 4 4; }
@test "negative" { check '1 2 0' -3 -1 -2; }
@test "int32-extremes" { check '1 2 0 3' -2147483648 2147483647 0 -2147483648; }
@test "sorted" { check '2 1 0' 1 2 3; }
@test "reversed" { check '0 1 2' 3 2 1; }

References

  1. heapq, Heap queue algorithm, Python documentation, the introduction; heappush_max; Priority Queue Implementation Notes
  2. PriorityQueue (Java SE 27 and JDK 27), the class description
  3. std::priority_queue, cppreference.com, the introduction; Template parameters
  4. PriorityQueue<TElement,TPriority> Class, .NET API reference, Remarks
  5. Package heap, Go standard library, Overview; type Interface
  6. Struct BinaryHeap, The Rust Standard Library, the description; Min-heap
  7. The Java Language Specification, Java SE 27 Edition, Chapter 15, 15.18.2 Additive Operators (+ and -) for Numeric Types
  8. sort(1), Linux manual page, DESCRIPTION

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source