Priority queue: Difference between revisions

m
Priority Qutue page fix highlighting...
No edit summary
m (Priority Qutue page fix highlighting...)
Line 33:
{{trans|Python}}
 
<langsyntaxhighlight lang=11l>V items = [(3, ‘Clear drains’), (4, ‘Feed cat’), (5, ‘Make tea’), (1, ‘Solve RC tasks’), (2, ‘Tax return’)]
minheap:heapify(&items)
L !items.empty
print(minheap:pop(&items))</langsyntaxhighlight>
 
{{out}}
Line 49:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program priorQueue64.s */
Line 421:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 436:
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight lang=Action!>CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
Line 541:
TestPop()
TestIsEmpty()
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Priority_queue.png Screenshot from Atari 8-bit computer]
Line 564:
Ada 2012 includes container classes for priority queues.
 
<langsyntaxhighlight lang=Ada>with Ada.Containers.Synchronized_Queue_Interfaces;
with Ada.Containers.Unbounded_Priority_Queues;
with Ada.Strings.Unbounded;
Line 605:
end loop;
end;
end Priority_Queues;</langsyntaxhighlight>
 
{{out}}
Line 612:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<langsyntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* program priorqueue.s */
Line 1,037:
pop {r2-r4}
bx lr @ return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,050:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>;-----------------------------------
PQ_TopItem(Queue,Task:=""){ ; remove and return top priority item
TopPriority := PQ_TopPriority(Queue)
Line 1,109:
TopPriority := TopPriority?TopPriority:P , TopPriority := TopPriority<P?TopPriority:P
return, TopPriority
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight lang=AutoHotkey>data =
(
3 Clear drains
Line 1,131:
MsgBox, 262208,, % (Task:="Feed cat") " priority = " PQ_Check(PQ,task)"`n`n" PQ_View(PQ)
^Esc::
ExitApp</langsyntaxhighlight>
 
=={{header|Axiom}}==
Axiom already has a heap domain for ordered sets.
We define a domain for ordered key-entry pairs and then define a priority queue using the heap domain over the pairs:
<langsyntaxhighlight lang=Axiom>)abbrev Domain ORDKE OrderedKeyEntry
OrderedKeyEntry(Key:OrderedSet,Entry:SetCategory): Exports == Implementation where
Exports == OrderedSet with
Line 1,162:
setelt(x:%,key:Key,entry:Entry) ==
insert!(construct(key,entry)$S,x)
entry</langsyntaxhighlight>For an example:<syntaxhighlight lang =Axiom>pq := empty()$PriorityQueue(Integer,String)
pq(3):="Clear drains";
pq(4):="Feed cat";
Line 1,168:
pq(1):="Solve RC tasks";
pq(2):="Tax return";
[extract!(pq) for i in 1..#pq]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,177:
=={{header|Batch File}}==
Batch has only a data structure, the environment that incidentally sorts itself automatically by key. The environment has a limit of 64K
<langsyntaxhighlight lang=Batch File>
@echo off
setlocal enabledelayedexpansion
Line 1,206:
:next
set order= %order:~-3%
goto:eof</langsyntaxhighlight>
{{out}}
<pre>
Line 1,218:
=={{header|C}}==
Using a dynamic array as a binary heap. Stores integer priority and a character pointer. Supports push and pop.
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
 
Line 1,289:
return 0;
}
</syntaxhighlight>
</lang>
{{output}}
<pre>Solve RC tasks
Line 1,298:
=== Pairing heap w/ generic data types ===
header file:
<syntaxhighlight lang=C>
<lang C>
typedef struct _pq_node_t {
long int key;
Line 1,317:
NEW_PQ_ELE(p, k); \
*(h) = heap_merge(((pq_node_t *) (p)), *(h))
</syntaxhighlight>
</lang>
implementation:
<syntaxhighlight lang=C>
<lang C>
#include <stdlib.h>
#include "pairheap.h"
Line 1,360:
return two_pass_merge(h->down);
}
</syntaxhighlight>
</lang>
usage:
<syntaxhighlight lang=C>
<lang C>
#include <stdio.h>
#include <string.h>
Line 1,399:
}
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,412:
 
===.NET 6 solution===
<langsyntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
 
Line 1,444:
5 Make tea
*/</langsyntaxhighlight>
 
===Pre-.NET 6 solution===
<langsyntaxhighlight lang=csharp>using System;
 
namespace PriorityQueue
Line 1,506:
}
}
}</langsyntaxhighlight>
 
'''Min Heap Priority Queue'''
Line 1,512:
{{works with|C sharp|C#|3.0+/DotNet 3.5+}}
The above code is not really a true Priority Queue as it does not allow duplicate keys; also, the SortedList on which it is based does not have O(log n) insertions and removals for random data as a true Priority Queue does. The below code implements a true Min Heap Priority Queue:
<langsyntaxhighlight lang=csharp>namespace PriorityQ {
using KeyT = UInt32;
using System;
Line 1,632:
return toSeq(fromSeq(sq)); }
}
}</langsyntaxhighlight>
 
The above class code offers a full set of static methods and properties:
Line 1,654:
 
The above code can be tested as per the page specification by the following code:
<langsyntaxhighlight lang=csharp> static void Main(string[] args) {
Tuple<uint, string>[] ins = { new Tuple<uint,string>(3u, "Clear drains"),
new Tuple<uint,string>(4u, "Feed cat"),
Line 1,676:
foreach (var e in MinHeapPQ<string>.toSeq(MinHeapPQ<string>.adjust((k, v) => new Tuple<uint,string>(6u - k, v), npq)))
Console.WriteLine(e); Console.WriteLine();
}</langsyntaxhighlight>
 
It tests building the queue the slow way using repeated "push"'s - O(n log n), the faster "fromSeq" (included in the "sort") - O(n), and also tests the "merge" and "adjust" methods.
Line 1,714:
The C++ standard library contains the <code>std::priority_queue</code> opaque data structure. It implements a max-heap.
 
<langsyntaxhighlight lang=cpp>#include <iostream>
#include <string>
#include <queue>
Line 1,733:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,747:
and use the heap operations to manipulate it:
 
<langsyntaxhighlight lang=cpp>#include <iostream>
#include <string>
#include <vector>
Line 1,776:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,789:
=={{header|Clojure}}==
 
<langsyntaxhighlight lang=clojure>user=> (use 'clojure.data.priority-map)
 
; priority-map can be used as a priority queue
Line 1,807:
; Merge priority-maps together
user=> (into p [["Wax Car" 4]["Paint Fence" 1]["Sand Floor" 3]])
{"Solve RC tasks" 1, "Paint Fence" 1, "Clear drains" 3, "Sand Floor" 3, "Wax Car" 4, "Feed cat" 4, "Make tea" 5}</langsyntaxhighlight>
 
=={{header|CLU}}==
Line 1,817:
must support the less-than operator.
 
<langsyntaxhighlight lang=clu>prio_queue = cluster [P, T: type] is new, empty, push, pop
where P has lt: proctype (P,P) returns (bool)
Line 1,911:
stream$putl(po, int$unparse(prio) || ": " || task)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>1: Solve RC tasks
Line 1,920:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang=coffeescript>
PriorityQueue = ->
# Use closure style for object creation (so no "new" required).
Line 1,999:
v = new_v
console.log "Final random element was #{v}"
</syntaxhighlight>
</lang>
 
output
Line 2,012:
First random element was 0.00002744467929005623
Final random element was 0.9999718656763434
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
In this task were implemented to versions of the functions, the non-destructive ones that will not change the state of the priority queue and the destructive ones that will change. The destructive ones work very similarly to the 'pop' and 'push' functions.
<langsyntaxhighlight lang=lisp>
;priority-queue's are implemented with association lists
(defun make-pq (alist)
Line 2,049:
(format t "~a~&" (remove-pq a))
(format t "~a~&" a)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,062:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang=oberon2>
MODULE PQueues;
IMPORT StdLog,Boxes;
Line 2,151:
END PQueues.
</syntaxhighlight>
</lang>
Interface extracted from the implementation
<langsyntaxhighlight lang=oberon2>
DEFINITION PQueues;
 
Line 2,176:
 
END PQueues.
</syntaxhighlight>
</lang>
Execute: ^Q PQueues.Test<br/>
Output:
Line 2,188:
 
=={{header|D}}==
<langsyntaxhighlight lang=d>import std.stdio, std.container, std.array, std.typecons;
 
void main() {
Line 2,202:
heap.removeFront();
}
}</langsyntaxhighlight>
{{out}}
<pre>Tuple!(int,string)(5, "Make tea")
Line 2,213:
{{libheader| Boost.Generics.Collection}}
Boost.Generics.Collection is part of [https://github.com/MaiconSoft/DelphiBoostLib DelphiBoostLib]
<langsyntaxhighlight lang=Delphi>program Priority_queue;
 
{$APPTYPE CONSOLE}
Line 2,230:
with Queue.DequeueEx do
Writeln(Priority, ', ', value);
end.</langsyntaxhighlight>
{{out}}
<pre>1, Solve RC tasks
Line 2,240:
=={{header|EchoLisp}}==
We use the built-in binary tree library. Each tree node has a datum (key . value). The functions (bin-tree-pop-first tree) and (bin-tree-pop-last tree) allow to extract the node with highest or lowest priority.
<langsyntaxhighlight lang=lisp>
(lib 'tree)
(define tasks (make-bin-tree 3 "Clear drains"))
Line 2,259:
(bin-tree-pop-last tasks) → (4 . "Feed 🐡")
; etc.
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang=elixir>defmodule Priority do
def create, do: :gb_trees.empty
Line 2,292:
end
 
Priority.task</langsyntaxhighlight>
 
{{out}}
Line 2,306:
=={{header|Erlang}}==
Using built in gb_trees module, with the suggested interface for this task.
<langsyntaxhighlight lang=Erlang>
-module( priority_queue ).
 
Line 2,335:
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,355:
 
The following Binomial Heap Priority Queue code has been adapted [http://cs.hubfs.net/topic/None/56608 from a version by "DeeJay"] updated for changes in F# over the intervening years, and implementing the O(1) "peekMin" mentioned in that post; in addition to the above standard priority queue functions, it also implements the "merge" function for which the Binomial Heap is particularly suited, taking O(log n) time rather than the usual O(n) (or worse) time:
<langsyntaxhighlight lang=fsharp>[<RequireQualifiedAccess>]
module PriorityQ =
 
Line 2,457:
let sort sq = sq |> fromSeq |> toSeq
 
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq</langsyntaxhighlight>
 
"isEmpty", "empty", and "peekMin" all have O(1) performance, "push" is O(1) amortized performance with O(log n) worst case, and the rest are O(log n) except for "fromSeq" (and thus "sort" and "adjust") which have O(n log n) performance since they use repeated "deleteMin" with one per entry.
Line 2,470:
 
The following code implementing a Min Heap Priority Queue is adapted from the [http://www.cl.cam.ac.uk/~lp15/MLbook/programs/sample4.sml ML PRIORITY_QUEUE code by Lawrence C. Paulson] including separating the key/value pairs as separate entries in the data structure for better comparison efficiency; it implements an efficient "fromSeq" function using reheapify for which the Min Heap is particularly suited as it has only O(n) instead of O(n log n) computational time complexity, which method is also used for the "adjust" and "merge" functions:
<langsyntaxhighlight lang=fsharp>[<RequireQualifiedAccess>]
module PriorityQ =
 
Line 2,602:
let toSeq pq = Seq.unfold popMin pq
 
let sort sq = sq |> fromSeq |> toSeq</langsyntaxhighlight>
 
The above code implements a "merge" function so that no internal sequence generation is necessary as generation of sequence iterators is quite inefficient in F# for a combined O(n) computational time complexity but a considerable reduction in the constant factor overhead.
Line 2,613:
 
As the Min Heap is usually implemented as a [http://opendatastructures.org/versions/edition-0.1e/ods-java/10_1_BinaryHeap_Implicit_Bi.html mutable array binary heap] after a genealogical tree based model invented by [https://en.wikipedia.org/wiki/Michael_Eytzinger Michael Eytzinger] over 400 years ago, the following "ugly imperative" code implements the Min Heap Priority Queue this way; note that the code could be implemented not using "ugly" mutable state variables other than the contents of the array (DotNet List which implements a growable array) but in this case the code would be considerably slower as in not much faster or slower than the functional version since using mutable side effects greatly reduces the number of operations:
<langsyntaxhighlight lang=fsharp>[<RequireQualifiedAccess>]
module PriorityQ =
 
Line 2,696:
let toSeq pq = Seq.unfold popMin pq
 
let sort sq = sq |> fromSeq |> toSeq</langsyntaxhighlight>
 
The comments for the above code are the same as for the functional version; the main difference is that the imperative code takes about two thirds of the time on average.
 
All of the above codes can be tested under the F# REPL using the following:
<langsyntaxhighlight lang=fsharp>> let testseq = [| (3u, "Clear drains");
(4u, "Feed cat");
(5u, "Make tea");
Line 2,719:
printfn ""
testpq |> MinHeap.adjust (fun k v -> uint32 (MinHeap.size testpq) - k, v)
|> MinHeap.toSeq |> Seq.iter (printfn "%A") // test adjust;;</langsyntaxhighlight>
 
to produce the following output:
Line 2,765:
=={{header|Factor}}==
Factor has priority queues implemented in the library: documentation is available at http://docs.factorcode.org/content/article-heaps.html (or by typing "heaps" help interactively in the listener).
<langsyntaxhighlight lang=factor><min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
Line 2,774:
] [
[ print ] slurp-heap
] bi</langsyntaxhighlight>
 
output:
<langsyntaxhighlight lang=factor>Solve RC tasks
Tax return
Clear drains
Feed cat
Make tea</langsyntaxhighlight>
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
<br>
<langsyntaxhighlight lang=forth>#! /usr/bin/gforth
 
\ Priority queue
Line 2,970:
>r 2 s" Tax return" r> >queue
 
drain-queue</langsyntaxhighlight>
 
{{out}}
Line 2,982:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang=Fortran>module priority_queue_mod
implicit none
 
Line 3,083:
! 2 -> Tax return
! 1 -> Solve RC tasks
</syntaxhighlight>
</lang>
 
 
=={{header|FreeBASIC}}==
{{trans|VBA}}
<langsyntaxhighlight lang=freebasic>Type Tupla
Prioridad As Integer
Tarea As String
Line 3,173:
Print t.Prioridad; " "; t.Tarea
Loop
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 3,181:
 
=={{header|FunL}}==
<langsyntaxhighlight lang=funl>import util.ordering
native scala.collection.mutable.PriorityQueue
 
Line 3,202:
 
while not q.isEmpty()
println( q.dequeue() )</langsyntaxhighlight>
 
{{out}}
Line 3,217:
Go's standard library contains the <code>container/heap</code> package, which which provides operations to operate as a heap any data structure that contains the <code>Push</code>, <code>Pop</code>, <code>Len</code>, <code>Less</code>, and <code>Swap</code> methods.
 
<langsyntaxhighlight lang=go>package main
 
import (
Line 3,259:
fmt.Println(heap.Pop(pq))
}
}</langsyntaxhighlight>
 
output:
Line 3,272:
=={{header|Groovy}}==
Groovy can use the built in java PriorityQueue class
<langsyntaxhighlight lang=groovy>import groovy.transform.Canonical
 
@Canonical
Line 3,289:
 
while (!empty) { println remove() }
}</langsyntaxhighlight>
 
Output:
Line 3,300:
=={{header|Haskell}}==
One of the best Haskell implementations of priority queues (of which there are many) is [http://hackage.haskell.org/package/pqueue pqueue], which implements a binomial heap.
<langsyntaxhighlight lang=haskell>import Data.PQueue.Prio.Min
 
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))</langsyntaxhighlight>
 
Although Haskell's standard library does not have a dedicated priority queue structure, one can (for most purposes) use the built-in <code>Data.Set</code> data structure as a priority queue, as long as no two elements compare equal (since Set does not allow duplicate elements). This is the case here since no two tasks should have the same name. The complexity of all basic operations is still O(log n) although that includes the "elemAt 0" function to retrieve the first element of the ordered sequence if that were required; "fromList" takes O(n log n) and "toList" takes O(n) time complexity. Alternatively, a <code>Data.Map.Lazy</code> or <code>Data.Map.Strict</code> can be used in the same way with the same limitations.
<langsyntaxhighlight lang=haskell>import qualified Data.Set as S
 
main = print (S.toList (S.fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))</langsyntaxhighlight>
{{out}}
<pre>[(1,"Solve RC tasks"),(2,"Tax return"),(3,"Clear drains"),(4,"Feed cat"),(5,"Make tea")]</pre>
 
Alternatively, a homemade min heap implementation:
<langsyntaxhighlight lang=haskell>data MinHeap a = Nil | MinHeap { v::a, cnt::Int, l::MinHeap a, r::MinHeap a }
deriving (Show, Eq)
 
Line 3,354:
(5, "Make tea"),
(1, "Solve RC tasks"),
(2, "Tax return")]</langsyntaxhighlight>
 
The above code is a Priority Queue but isn't a [https://en.wikipedia.org/wiki/Binary_heap Min Heap based on a Binary Heap] for the following reasons: 1) it does not preserve the standard tree structure of the binary heap and 2) the tree balancing can be completely destroyed by some combinations of "pop" operations. The following code is a true purely functional Min Heap implementation and as well implements the extra optional features of Min Heap's that it can build a new Min Heap from a list in O(n) amortized time rather than the O(n log n) amortized time (for a large number of randomly ordered entries) by simply using repeated "push" operations; as well as the standard "push", "peek", "delete" and "pop" (combines the previous two). As well as the "fromList", "toList", and "sort" functions (the last combines the first two), it also has an "isEmpty" function to test for the empty queue, an "adjust" function that applies a function to every entry in the queue and reheapifies in O(n) amortized time and also the "replaceMin" function which is about twice as fast on the average as combined "delete" followed by "push" operations:
<langsyntaxhighlight lang=haskell>data MinHeap kv = MinHeapEmpty
| MinHeapLeaf !kv
| MinHeapNode !kv {-# UNPACK #-} !Int !(MinHeap a) !(MinHeap a)
Line 3,480:
 
sortPQ :: (Ord kv) => [kv] -> [kv]
sortPQ ls = toListPQ $ fromListPQ ls</langsyntaxhighlight>
 
If one is willing to forgo the fast O(1) "size" function and to give up strict conformance to the Heap tree structure (where rather than building each new level until each left node is full to that level before increasing level to the right, a new level is built by promoting leaves to branches only containing left leaves until all branches have left leaves before filling any right leaves of that level) although having even better tree balancing and therefore at least as high efficiency, one can use the following code adapted from the [http://www.cl.cam.ac.uk/~lp15/MLbook/programs/sample4.sml ''ML'' PRIORITY_QUEUE code by Lawrence C. Paulson] including separating the key/value pairs as separate entries in the data structure for better comparison efficiency; as noted in the code comments, a "size" function to output the number of elements in the queue (fairly quickly in O((log n)^2)), an "adjust" function to apply a function to all elements and reheapify in O(n) time, and a "merge" function to merge two queues has been added to the ML code:
<langsyntaxhighlight lang=haskell>data PriorityQ k v = Mt
| Br !k v !(PriorityQ k v) !(PriorityQ k v)
deriving (Eq, Ord, Read, Show)
Line 3,586:
 
sortPQ :: (Ord k) => [(k, v)] -> [(k, v)]
sortPQ ls = toListPQ $ fromListPQ ls</langsyntaxhighlight>
 
The above codes compile but do not run with GHC Haskell version 7.8.3 using the LLVM back end with LLVM version 3.4 and full optimization turned on under Windows 32; they were tested under Windows 64 and 32 using the Native Code Generator back end with full optimization. With GHC Haskell version 7.10.1 they compile and run with or without LLVM 3.5.1 for 32-bit Windows (64-bit GHC Haskell under Windows does not run with LLVM for version 7.10.1), with a slight execution speed advantage to using LLVM.
Line 3,595:
 
The above codes when tested with the following "main" function (with a slight modification for the first test when the combined kv entry is used):
<langsyntaxhighlight lang=haskell>testList = [ (3, "Clear drains"),
(4, "Feed cat"),
(5, "Make tea"),
Line 3,612:
mapM_ print $ toListPQ $ mergePQ testPQ testPQ
putStrLn "" -- test adjust
mapM_ print $ toListPQ $ adjustPQ (\x y -> (x * (-1), y)) testPQ</langsyntaxhighlight>
 
has the output as follows:
Line 3,658:
<tt>Closure</tt> is used to allow the queue to order lists based on
their first element. The solution only works in Unicon.
<langsyntaxhighlight lang=Unicon>import Utils # For Closure class
import Collections # For Heap (dense priority queue) class
 
Line 3,671:
while task := pq.get() do write(task[1]," -> ",task[2])
end
</syntaxhighlight>
</lang>
Output when run:
<pre>
Line 3,685:
Implementation:
 
<langsyntaxhighlight lang=j>coclass 'priorityQueue'
 
PRI=: ''
Line 3,707:
QUE=: y}.QUE
r
)</langsyntaxhighlight>
 
Efficiency is obtained by batching requests. Size of batch for insert is determined by size of arguments. Size of batch for topN is its right argument.
Line 3,713:
Example:
 
<langsyntaxhighlight lang=j> Q=: conew'priorityQueue'
3 4 5 1 2 insert__Q 'clear drains';'feed cat';'make tea';'solve rc task';'tax return'
>topN__Q 1
Line 3,721:
clear drains
tax return
solve rc task</langsyntaxhighlight>
 
=={{header|Java}}==
Java has a <code>PriorityQueue</code> class. It requires either the elements implement <code>Comparable</code>, or you give it a custom <code>Comparator</code> to compare the elements.
 
<langsyntaxhighlight lang=java>import java.util.PriorityQueue;
 
class Task implements Comparable<Task> {
Line 3,756:
System.out.println(pq.remove());
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,771:
The special key "priorities" is used to store the priorities in a sorted array. Since "sort" is fast we will use that rather than optimizing insertion in the priorities array.
 
We assume that if an item of a given priority is already in the priority queue, there is no need to add it again.<langsyntaxhighlight lang=jq># In the following, pq stands for "priority queue".
 
# Add an item with the given priority (an integer,
Line 3,820:
def prioritize:
. as $list | {} | pq_add_tasks($list) | pq_pop_tasks ;
</syntaxhighlight>
</lang>
The specific task:
<syntaxhighlight lang=jq>
<lang jq>
[ [3, "Clear drains"],
[4, "Feed cat"],
Line 3,829:
[2, "Tax return"]
] | prioritize
</syntaxhighlight>
</lang>
{{Out}}
"Solve RC tasks"
Line 3,839:
=={{header|Julia}}==
Julia has built-in support for priority queues, though the <code>PriorityQueue</code> type is not exported by default. Priority queues are a specialization of the <code>Dictionary</code> type having ordered values, which serve as the priority. In addition to all of the methods of standard dictionaries, priority queues support: <code>enqueue!</code>, which adds an item to the queue, <code>dequeue!</code> which removes the lowest priority item from the queue, returning its key, and <code>peek</code>, which returns the (key, priority) of the lowest priority entry in the queue. The ordering behavior of the queue, which by default is its value sort order (typically low to high), can be set by passing an order directive to its constructor. For this task, <code>Base.Order.Reverse</code> is used to set-up the <code>task</code> queue to return tasks from high to low priority.
<langsyntaxhighlight lang=Julia>
using Base.Collections
 
Line 3,858:
dequeue!(task)
println(" \"", t, "\" has priority ", p)
end</langsyntaxhighlight>
 
{{out}}
Line 3,871:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang=scala>import java.util.PriorityQueue
 
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
Line 3,890:
"Tax return" priority 2))
while (q.any()) println(q.remove())
}</langsyntaxhighlight>
{{out}}
<pre>Task(priority=1, name=Solve RC tasks)
Line 3,899:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang=lasso>define priorityQueue => type {
data
store = map,
Line 3,957:
while(not #test->isEmpty) => {
stdout(#test->pop)
}</langsyntaxhighlight>
 
{{out}}
Line 3,966:
This implementation uses a table with priorities as keys and queues as values. Queues for each priority are created when putting items as needed and are shrunk as necessary when popping items and removed when they are empty. Instead of using a plain array table for each queue, the technique shown in the Lua implementation from the [[Queue/Definition#Lua | Queue]] task is used. This avoids having to use <code>table.remove(t, 1)</code> to get and remove the first queue element, which is rather slow for big tables.
 
<langsyntaxhighlight lang=lua>PriorityQueue = {
__index = {
put = function(self, p, v)
Line 4,015:
for prio, task in pq.pop, pq do
print(string.format("Popped: %d - %s", prio, task))
end</langsyntaxhighlight>
 
'''Output:'''
Line 4,032:
The implementation is faster than the Python implementations below using <code>queue.PriorityQueue</code> or <code>heapq</code>, even when comparing the standard Lua implementation against [[PyPy]] and millions of tasks are added to the queue. With LuaJIT it is yet faster. The following code measures the time needed to add 10<sup>7</sup> tasks with a random priority between 1 and 1000 and to retrieve them from the queue again in order.
 
<langsyntaxhighlight lang=lua>-- Use socket.gettime() for benchmark measurements
-- since it has millisecond precision on most systems
local socket = require("socket")
Line 4,071:
end
 
print(string.format("Elapsed: %.3f ms.", (socket.gettime() - start) * 1000))</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 4,077:
 
===Using unordered array===
<langsyntaxhighlight lang=M2000 Interpreter>
Module UnOrderedArray {
Class PriorityQueue {
Line 4,194:
}
UnOrderedArray
</syntaxhighlight>
</lang>
 
===Using a stack with arrays as elements===
Every insertion push item using binary search in proper position. Pop is very fast.
<langsyntaxhighlight lang=M2000 Interpreter>
Module PriorityQueue {
a= ( (3, "Clear drains"), (4 ,"Feed cat"), ( 5 , "Make tea"), ( 1 ,"Solve RC tasks"), ( 2 , "Tax return"))
Line 4,260:
PriorityQueue
 
</syntaxhighlight>
</lang>
 
===Using a stack with Groups as elements===
This is the same as previous but now we use a group (a user object for M2000). InsertPQ is the same as before. Lambda comp has change only. We didn't use pointers to groups. All groups here works as values, so when we get a peek we get a copy of group in top position. All members of a group may not values, so if we have a pointer to group then we get a copy of that pointer, but then we can make changes and that changes happen for the group which we get the copy.
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module PriorityQueueForGroups {
class obj {
Line 4,323:
}
PriorityQueueForGroups
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang=mathematica>push = Function[{queue, priority, item},
queue = SortBy[Append[queue, {priority, item}], First], HoldFirst];
pop = Function[queue,
Line 4,335:
If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst];
merge = Function[{queue1, queue2},
SortBy[Join[queue1, queue2], First], HoldAll];</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang=mathematica>queue = {};
push[queue, 3, "Clear drains"];
push[queue, 4, "Feed cat"];
Line 4,349:
queue1 = {};
push[queue1, 6, "Drink tea"];
Print[merge[queue, queue1]];</langsyntaxhighlight>
 
Output:
Line 4,360:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang=maxima>/* Naive implementation using a sorted list of pairs [key, [item[1], ..., item[n]]].
The key may be any number (integer or not). Items are extracted in FIFO order. */
 
Line 4,441:
"call friends"
"serve cider"
"savour !"</langsyntaxhighlight>
 
=={{header|Mercury}}==
Mercury comes with an efficient, albeit simple, priority queue in its standard library. The build_pqueue/2 predicate in the code below inserts the test data in arbitrary order. display_pqueue/3, in turn, removes one K/V pair at a time, displaying the value. Compiling and running the supplied program results in all tasks being displayed in priority order as expected.
 
<langsyntaxhighlight lang=mercury>:- module test_pqueue.
 
:- interface.
Line 4,480:
main(!IO) :-
build_pqueue(pqueue.init, PQO),
display_pqueue(PQO, !IO).</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang=nim>type
PriElem[T] = tuple
data: T
Line 4,543:
 
while p.count > 0:
echo p.pop()</langsyntaxhighlight>
{{out}}
<pre>(data: Solve RC tasks, pri: 1)
Line 4,552:
 
''' Using Nim HeapQueue'''
<langsyntaxhighlight lang=Nim>import HeapQueue
 
var pq = newHeapQueue[(int, string)]()
Line 4,563:
 
while pq.len() > 0:
echo pq.pop()</langsyntaxhighlight>
 
{{out}}
Line 4,573:
 
''' Using Nim tables'''
<langsyntaxhighlight lang=Nim>import tables
 
var
Line 4,590:
pq.del(i)
main()</langsyntaxhighlight>
{{out}}
<pre>1: Solve RC tasks
Line 4,602:
The priority queue used in this example is not actually written in Objective-C. It is part of Apple's (C-based) Core Foundation library, which is included with in Cocoa on Mac OS X and iOS. Its interface is a C function interface, which makes the code very ugly. Core Foundation is not included in GNUStep or other Objective-C APIs.
 
<langsyntaxhighlight lang=objc>#import <Foundation/Foundation.h>
 
const void *PQRetain(CFAllocatorRef allocator, const void *ptr) {
Line 4,665:
}
return 0;
}</langsyntaxhighlight>
 
log:
Line 4,680:
Holger Arnold's [http://holgerarnold.net/software/ OCaml base library] provides a [http://holgerarnold.net/software/ocaml/doc/base/PriorityQueue.html PriorityQueue] module.
 
<langsyntaxhighlight lang=ocaml>module PQ = Base.PriorityQueue
 
let () =
Line 4,696:
PQ.remove_first pq;
print_endline task
done</langsyntaxhighlight>
 
testing:
Line 4,708:
Although OCaml's standard library does not have a dedicated priority queue structure, one can (for most purposes) use the built-in Set data structure as a priority queue, as long as no two elements compare equal (since Set does not allow duplicate elements). This is the case here since no two tasks should have the same name. Note that Set is a functional, persistent data structure, so we derive new priority queues from the old ones functionally, rather than modifying them imperatively; the complexity is still O(log n).
{{works with|OCaml|4.02+}}
<langsyntaxhighlight lang=ocaml>module PQSet = Set.Make
(struct
type t = int * string (* pair of priority and task name *)
Line 4,729:
aux (PQSet.remove task pq')
end
in aux pq</langsyntaxhighlight>
{{out}}
<pre>
Line 4,905:
(buffer empty)
*/
</syntaxhighlight>
</lang>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang=Pascal>
program PriorityQueueTest;
 
Line 4,983:
Queue.free;
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
There are a few implementations on CPAN. Following uses <code>Heap::Priority</code>[http://search.cpan.org/~fwojcik/Heap-Priority-0.11/Priority.pm]
<langsyntaxhighlight lang=perl>use 5.10.0;
use strict;
use Heap::Priority;
Line 5,000:
["Tax return", 2];
 
say while ($_ = $h->pop);</langsyntaxhighlight>output<lang>Make tea
Feed cat
Clear drains
Tax return
Solve RC tasks</langsyntaxhighlight>
===IBM card sorter version===
<langsyntaxhighlight lang=perl>#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Priority_queue
Line 5,038:
delete $bins[-1] while @bins and @{ $bins[-1] // [] } == 0;
shift @{ $bins[-1] // [] };
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,052:
Dictionary based solution. Allows duplicate tasks, FIFO within priority, and uses a callback-style method of performing tasks.<br>
Assumes 5 is the highest priority and should be done first, for 1 first just delete the ",true" on traverse_dict calls.
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tasklist</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
Line 5,108:
<span style="color: #0000FF;">?</span><span style="color: #008000;">"==="</span>
<span style="color: #000000;">list_tasks</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,128:
(I needed this for [[Taxicab_numbers#Phix|Taxicab_numbers]])<br>
The bulk of this code now forms builtins/pqueue.e (not properly documented at the time, but now is, see below)
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">pq</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 5,185:
<span style="color: #0000FF;">?</span><span style="color: #000000;">pqPop</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</langsyntaxhighlight>-->
{{out}}
The optional initial set_rand() makes it slightly more amusing.<br>
Line 5,204:
=== builtin ===
If you omit MAX_HEAP or (same thing) specify MIN_HEAP, the output'll be 1..5
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tasklist</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">pq_new</span><span style="color: #0000FF;">(</span><span style="color: #004600;">MAX_HEAP</span><span style="color: #0000FF;">)</span>
Line 5,218:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">priority</span><span style="color: #0000FF;">,</span><span style="color: #000000;">task</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,229:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight lang=Phixmonti>/# Rosetta Code problem: http://rosettacode.org/wiki/Priority_queue
by Galileo, 05/2022 #/
 
Line 5,237:
( 3 "Clear drains" ) 0 put ( 4 "Feed cat" ) 0 put ( 5 "Make tea" ) 0 put ( 1 "Solve RC tasks" ) 0 put ( 2 "Tax return" ) 0 put
sort pop swap print pstack
</syntaxhighlight>
</lang>
{{out}}
<pre>[1, "Solve RC tasks"]
Line 5,247:
{{works with|PHP|5.3+}}
PHP's <code>SplPriorityQueue</code> class implements a max-heap. PHP also separately has <code>SplHeap</code>, <code>SplMinHeap</code>, and <code>SplMaxHeap</code> classes.
<langsyntaxhighlight lang=php><?php
$pq = new SplPriorityQueue;
 
Line 5,263:
print_r($pq->extract());
}
?></langsyntaxhighlight>
 
Output:
Line 5,296:
{{works with|PHP|5.3+}}
The difference between <code>SplHeap</code> and <code>SplPriorityQueue</code> is that <code>SplPriorityQueue</code> takes the data and the priority as two separate arguments, and the comparison is only made on the priority; whereas <code>SplHeap</code> takes only one argument (the element), and the comparison is made on that directly. In all of these classes it is possible to provide a custom comparator by subclassing the class and overriding its <code>compare</code> method.
<langsyntaxhighlight lang=php><?php
$pq = new SplMinHeap;
Line 5,308:
print_r($pq->extract());
}
?></langsyntaxhighlight>
 
Output:
Line 5,341:
=={{header|Picat}}==
Picat has built-in support for min and max heaps.
<langsyntaxhighlight lang=Picat>main =>
Tasks = [[3,"Clear drains"],
[4,"Feed cat"],
Line 5,357:
nl,
println("Pop the elements from the queue:"),
println([Heap.heap_pop() : _ in 1..Heap.heap_size]).</langsyntaxhighlight>
 
{{out}}
Line 5,373:
 
The heaps creation functions can take the task list as argument:
<langsyntaxhighlight lang=Picat> Tasks = [[3,"Clear drains"],
[4,"Feed cat"],
[5,"Make tea"],
Line 5,379:
[2,"Tax return"]],
Heap = new_min_heap(Tasks),
println([Heap.heap_pop() : _ in 1..Heap.heap_size]).</langsyntaxhighlight>
 
 
=={{header|PicoLisp}}==
The following implementation imposes no limits. It uses a [http://software-lab.de/doc/refI.html#idx binary tree] for storage. The priority levels may be numeric, or of any other type.
<langsyntaxhighlight lang=PicoLisp># Insert item into priority queue
(de insertPQ (Queue Prio Item)
(idx Queue (cons Prio Item) T) )
Line 5,401:
# Merge second queue into first
(de mergePQ (Queue1 Queue2)
(balance Queue1 (sort (conc (idx Queue1) (idx Queue2)))) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang=PicoLisp># Two priority queues
(off Pq1 Pq2)
 
Line 5,420:
# Remove and print all items from first queue
(while Pq1
(println (removePQ 'Pq1)) )</langsyntaxhighlight>
Output:
<pre>(Solve RC tasks)
Line 5,428:
(Make tea)</pre>
=== Alternative version using a pairing heap: ===
<langsyntaxhighlight lang=PicoLisp>
(de heap-first (H) (car H))
 
Line 5,452:
(de heap-rest (H)
("merge-pairs" (cdr H)))
</syntaxhighlight>
</lang>
Test:
<langsyntaxhighlight lang=PicoLisp>
(setq H NIL)
(for
Line 5,470:
 
(bye)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,485:
 
Example of use :
<langsyntaxhighlight lang=Prolog>priority-queue :-
TL0 = [3-'Clear drains',
4-'Feed cat'],
Line 5,513:
heap_to_list(Heap4, TL2),
writeln('Content of the queue'), maplist(writeln, TL2).
</syntaxhighlight>
</lang>
The output :
<pre>1 ?- priority-queue.
Line 5,537:
The map stores the elements of a given priority in a FIFO list.
Priorities can be any signed 32 value.
<langsyntaxhighlight lang=purebasic>Structure taskList
List description.s() ;implements FIFO queue
EndStructure
Line 5,655:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Solve RC tasks
Line 5,675:
 
The data structures in the "queue" module are synchronized multi-producer, multi-consumer queues for multi-threaded use. They can however handle this task:
<langsyntaxhighlight lang=python>>>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
Line 5,690:
(4, 'Feed cat')
(5, 'Make tea')
>>> </langsyntaxhighlight>
 
;Help text for queue.PriorityQueue:
<langsyntaxhighlight lang=python>>>> import queue
>>> help(queue.PriorityQueue)
Help on class PriorityQueue in module queue:
Line 5,799:
| list of weak references to the object (if defined)
 
>>> </langsyntaxhighlight>
 
===Using heapq===
Line 5,805:
 
Although one can use the heappush method to add items individually to a heap similar to the method used in the PriorityQueue example above, we will instead transform the list of items into a heap in one go then pop them off one at a time as before.
<langsyntaxhighlight lang=python>>>> from heapq import heappush, heappop, heapify
>>> items = [(3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")]
>>> heapify(items)
Line 5,817:
(4, 'Feed cat')
(5, 'Make tea')
>>> </langsyntaxhighlight>
 
;Help text for module heapq:
<langsyntaxhighlight lang=python>>>> help('heapq')
Help on module heapq:
 
Line 5,908:
 
 
>>> </langsyntaxhighlight>
 
 
Line 5,915:
For more examples uf usage, see [[Sorting algorithms/Heapsort#Quackery]] and [[Huffman coding#Quackery]]
 
<langsyntaxhighlight lang=Quackery>( ***** priotity queue ***** )
 
[ stack ] is heap.pq ( --> s )
Line 6,012:
swap echo say ": "
echo$ cr ]
drop</langsyntaxhighlight>
 
{{out}}
Line 6,025:
=={{header|R}}==
Using closures:
<langsyntaxhighlight lang=R>PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
Line 6,050:
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}</langsyntaxhighlight>With output:<syntaxhighlight lang =R>1 : Solve RC tasks
2 : Tax return
3 : Clear drains
4 : Feed cat
5 : Make tea</langsyntaxhighlight>A similar implementation using R5 classes:<langsyntaxhighlight lang=R>PriorityQueue <-
setRefClass("PriorityQueue",
fields = list(keys = "numeric", values = "list"),
Line 6,070:
},
empty = function() length(keys) == 0
))</langsyntaxhighlight>The only change in the example would be in the instantiation:<syntaxhighlight lang =R>pq <- PriorityQueue$new()</langsyntaxhighlight>.
 
=={{header|Racket}}==
This solution implements priority queues on top of heaps.
<langsyntaxhighlight lang=racket>
#lang racket
(require data/heap)
Line 6,099:
(remove-min!)
(remove-min!)
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang=racket>
"Solve RC tasks"
"Tax return"
Line 6,107:
"Feed cat"
"Make tea"
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 6,115:
The tasks are stored internally as an array of FIFO buffers, so multiple tasks of the same priority level will be returned in the order they were stored.
 
<langsyntaxhighlight lang=perl6>class PriorityQueue {
has @!tasks;
 
Line 6,142:
}
say $pq.get until $pq.is-empty;</langsyntaxhighlight>
 
{{out}}
Line 6,157:
===version 1===
Programming note: &nbsp; this REXX version allows any number (with or without decimals, say, '''5.7''') for the priority, including negative numbers.
<langsyntaxhighlight lang=rexx>/*REXX program implements a priority queue with insert/display/delete the top task.*/
#=0; @.= /*0 tasks; nullify the priority queue.*/
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
Line 6,178:
if top=='' | _>top then do; top=_; top#=j; end
end /*j*/
return top#</langsyntaxhighlight>
{{out|output}}
<pre>
Line 6,195:
 
===version 2===
<langsyntaxhighlight lang=rexx>/*REXX pgm implements a priority queue; with insert/show/delete top task*/
n=0
task.=0 /* for the sake of task.0done.* */
Line 6,236:
task.0done.j=1
todo=todo-1
return res</langsyntaxhighlight>
{{out}}
<pre>------ inserting tasks.
Line 6,258:
=={{header|Ruby}}==
A naive, inefficient implementation
<langsyntaxhighlight lang=ruby>class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
Line 6,339:
puts pq3.pop
end
puts "peek : #{pq3.peek}"</langsyntaxhighlight>
 
{{out}}
Line 6,366:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>sqliteconnect #mem, ":memory:"
#mem execute("CREATE TABLE queue (priority float,descr text)")
 
Line 6,410:
print priority;" ";descr$
next i
RETURN</langsyntaxhighlight>
{{out}}
<pre> -------------- Find first priority ---------------------
Line 6,427:
 
=={{header|Rust}}==
<langsyntaxhighlight lang=rust>use std::collections::BinaryHeap;
use std::cmp::Ordering;
use std::borrow::Cow;
Line 6,474:
println!("{}", item.task);
}
}</langsyntaxhighlight>
{{out}}
<pre>Solve RC tasks
Line 6,484:
=={{header|SAS}}==
Using macros in a SAS data step:
<langsyntaxhighlight lang=sas>%macro HeapInit(size=1000,nchar=20);
do;
_len = 0;
Line 6,579:
%HeapPop;
end;
run;</langsyntaxhighlight>
{{output}}
<pre>1 Solve RC tasks
Line 6,588:
 
An implementation using <code>proc ds2</code> may be more structured:
<langsyntaxhighlight lang=sas>proc ds2;
package Heap / overwrite=yes;
dcl int _entryorder _size _len _entryOrders[1000];
Line 6,697:
end;
enddata;
run;</langsyntaxhighlight>
 
=={{header|Scala}}==
Scala has a class PriorityQueue in its standard library.
<langsyntaxhighlight lang=scala>import scala.collection.mutable.PriorityQueue
case class Task(prio:Int, text:String) extends Ordered[Task] {
def compare(that: Task)=that.prio compare this.prio
Line 6,709:
var q=PriorityQueue[Task]() ++ Seq(Task(3, "Clear drains"), Task(4, "Feed cat"),
Task(5, "Make tea"), Task(1, "Solve RC tasks"), Task(2, "Tax return"))
while(q.nonEmpty) println(q dequeue)</langsyntaxhighlight>
Output:
<pre>Task(1,Solve RC tasks)
Line 6,717:
Task(5,Make tea)</pre>
Instead of deriving the class from Ordering an implicit conversion could be provided.
<langsyntaxhighlight lang=scala>case class Task(prio:Int, text:String)
implicit def taskOrdering=new Ordering[Task] {
def compare(t1:Task, t2:Task):Int=t2.prio compare t1.prio
}</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
We use New to create an object instance -- in this case (for simplicity) based on the script itself, which is named PriorityQueue. The Tell command or dot notation are then used to send messages directly to that object.
<langsyntaxhighlight lang=sensetalk>
// PriorityQueue.script
set Tasks to a new PriorityQueue
Line 6,765:
return (priority of each && task of each for each item of my queue) joined by return
end report
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,786:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang=ruby>class PriorityQueue {
has tasks = []
 
Line 6,815:
}
 
say pq.get while !pq.is_empty</langsyntaxhighlight>
 
{{out}}
Line 6,833:
Note: this is a max-heap
 
<langsyntaxhighlight lang=sml>structure TaskPriority = struct
type priority = int
val compare = Int.compare
Line 6,861:
in
aux pq
end</langsyntaxhighlight>
 
testing:
Line 6,876:
 
Using <code>mata</code>, which has 1-based arrays:
<langsyntaxhighlight lang=stata>mata
struct Node {
real scalar time
Line 6,978:
testHeap(0)
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 7,001:
You can use <code>CFBinaryHeap</code> from Core Foundation, but it is super ugly due to the fact that <code>CFBinaryHeap</code> operates on generic pointers, and you need to convert back and forth between that and objects.
{{works with|Swift|2.x}}
<langsyntaxhighlight lang=swift>class Task : Comparable, CustomStringConvertible {
var priority : Int
var name: String
Line 7,056:
while pq.count != 0 {
print(pq.pop())
}</langsyntaxhighlight>
 
{{out}}
Line 7,069:
=={{header|Tcl}}==
{{tcllib|struct::prioqueue}}
<langsyntaxhighlight lang=tcl>package require struct::prioqueue
 
set pq [struct::prioqueue]
Line 7,086:
# Remove the front-most item from the priority queue
puts [$pq get]
}</langsyntaxhighlight>
Which produces this output:
<pre>
Line 7,162:
For b@ = Set(b, b+1) To a@ + 1 Step -1: @(b@) = @(b@-1) : Next
Return
</langsyntaxhighlight>
{{Out}}
First an entry is dequeued from an empty queue. Then all entries are inserted and listed. Finally, another entry is dequeued and the remainder of the entries is listed again.
Line 7,184:
 
=={{header|VBA}}==
<langsyntaxhighlight lang=VB>Type Tuple
Priority As Integer
Data As String
Line 7,262:
Debug.Print t.Priority, t.Data
Loop
End Sub</langsyntaxhighlight>{{out}}<pre>1 Solve RC tasks
2 Tax return
3 Clear drains
Line 7,271:
=={{header|VBScript}}==
I wrote this priority queue in a class. It uses a dynamic array to implement the class. Function out_of_order must be adapted to the data. Run it with CScript.
<syntaxhighlight lang=vb>
<lang vb>
option explicit
Class prio_queue
Line 7,377:
set queue= nothing
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 7,392:
{{libheader|Wren-queue}}
The above module contains a PriorityQueue class. Unlike some other languages here, the higher the number, the higher the priority. So the 'Make tea' task has the highest priority and, thankfully, the cat has a good chance of being fed!
<langsyntaxhighlight lang=ecmascript>import "/queue" for PriorityQueue
 
var tasks = PriorityQueue.new()
Line 7,403:
var t = tasks.pop()
System.print(t)
}</langsyntaxhighlight>
 
{{out}}
Line 7,422:
The <code>'PUSH</code> method never needs to search down the levels. The efficiency bottleneck here is probably the implementation of <code>NCONC</code> (used for adding the new item to the end of the queue at the relevant level). A priority <i>stack</i>, with first in / last out at each priority level rather than first in / first out, would be faster.
 
<langsyntaxhighlight lang=lisp>(define-class priority-queue
(instance-variables queue lowest-priority most-urgent) )
 
Line 7,456:
 
(define-method (priority-queue 'emptyp)
(and (= most-urgent lowest-priority) (null (vector-ref queue most-urgent))) )</langsyntaxhighlight>
 
The example uses strings, but the data items stored in the priority queue can be of any type (including the empty list—or even other priority queues).
<langsyntaxhighlight lang=lisp>(define pq (priority-queue 'new 5))
 
(pq 'push "Clear drains" 3)
Line 7,465:
(pq 'push "Make tea" 5)
(pq 'push "Solve RC tasks" 1)
(pq 'push "Tax return" 2)</langsyntaxhighlight>
{{out}}
Items are popped beginning from the most urgent:
<langsyntaxhighlight lang=lisp>[1] (pq 'pop)
 
"Solve RC tasks"
[2] (pq 'pop)
 
"Tax return"</langsyntaxhighlight>
Within each priority level, new items are pushed onto the end and popped from the beginning of the list (a queue is a first in / first out data structure):
<langsyntaxhighlight lang=lisp>[3] (pq 'push "Answer emails" 4)
 
("Feed cat" "Answer emails")</langsyntaxhighlight>
Attempting to push with an invalid priority value returns the empty list, i.e. false:
<langsyntaxhighlight lang=lisp>[4] (pq 'push "Weed garden" 17)
 
()</langsyntaxhighlight>
<code>'EMPTYP</code> returns false if the priority queue is not empty:
<langsyntaxhighlight lang=lisp>[5] (pq 'emptyp)
 
()</langsyntaxhighlight>
<code>'PEEK</code> non-destructively returns the item that would be popped if you called <code>'POP</code>:
<langsyntaxhighlight lang=lisp>[6] (pq 'peek)
 
"Clear drains"</langsyntaxhighlight>
If you want to examine a whole priority queue, the built-in <code>'SHOW</code> method allows you to do so:
<langsyntaxhighlight lang=scheme>[7] (pq 'show)
 
Object is #<Object:PRIORITY-QUEUE #x4e2cba8>, Class is #<Class:PRIORITY-QUEUE #x4e254c8>
Line 7,498:
LOWEST-PRIORITY = 5
MOST-URGENT = 3
#<Object:PRIORITY-QUEUE #x4e2cba8></langsyntaxhighlight>
Once all the items have been popped, the priority queue is empty and <code>'EMPTYP</code> then returns true:
<langsyntaxhighlight lang=lisp>[8] (pq 'pop)
 
"Clear drains"
Line 7,514:
[12] (pq 'emptyp)
 
#T</langsyntaxhighlight>
Attempting to pop from an empty priority queue returns false:
<langsyntaxhighlight lang=lisp>[13] (pq 'pop)
 
()</langsyntaxhighlight>
 
=={{header|Zig}}==
Line 7,526:
Save the following code as <code>priority_queue.zig</code>, and run the tests using <code>zig test priority_queue.zig</code>.
 
<langsyntaxhighlight lang=Zig>
const std = @import("std");
const PriorityQueue = std.PriorityQueue;
Line 7,612:
}
 
</syntaxhighlight>
</lang>
 
Sample output:
 
<langsyntaxhighlight lang=Zig>
$ zig test priority_queue.zig
Test [1/2] test "priority queue (max heap)"...
Line 7,633:
 
All 2 tests passed.
</syntaxhighlight>
</lang>
 
=={{header|zkl}}==
This solution uses a [hopefully small] fixed number of priorities, each of which has an unordered list of tasks. This allows O(1) insertions, O(p) for retrievals (p is the number of priorities).
<langsyntaxhighlight lang=zkl>class PQ{
fcn init(numLevels=10){ // 0..numLevels, bigger # == lower priorty
var [const] queue=(1).pump(numLevels+1,List.createLong(numLevels).write,L().copy);
Line 7,656:
fcn walker{ state.clear().append(0,0); Walker(next) } // iterator front end
fcn toString{ "PQ(%d) items".fmt(queue.reduce(fcn(sum,q){ sum+q.len() },0)) }
}</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>pq:=PQ();
foreach x in
(T("Clear drains",3, "Feed cat",4, "Make tea",5, "Solve RC tasks",1, "Tax return",2,
Line 7,669:
println("ToDo list:");
foreach item in (pq){ item.println() }
pq.println();</langsyntaxhighlight>
{{out}}
<pre>
474

edits