Double-ended priority queue

In computer science, a double-ended priority queue (DEPQ)[1] or double-ended heap[2] is a data structure similar to a priority queue or heap, but allows for efficient removal of both the maximum and minimum, according to some ordering on the keys (items) stored in the structure. Every element in a DEPQ has a priority or value. In a DEPQ, it is possible to remove the elements in both ascending as well as descending order.[3]

Operations

UML class diagram of a double-ended priority queue.
UML class diagram of a double-ended priority queue.

A double-ended priority queue features the following operations:

isEmpty()
Checks if DEPQ is empty and returns true if empty.
size()
Returns the total number of elements present in the DEPQ.
getMin()
Returns the element having least priority.
getMax()
Returns the element having highest priority.
put(x)
Inserts the element x in the DEPQ.
removeMin()
Removes an element with minimum priority and returns this element.
removeMax()
Removes an element with maximum priority and returns this element.

Also, the priority of any element can be changed once it has been inserted in the DEPQ.[4]

Implementation

Double-ended priority queues can be built from balanced binary search trees (where the minimum and maximum elements are the leftmost and rightmost leaves, respectively), or using specialized data structures like min-max heap and pairing heap.

Generic methods of arriving at double-ended priority queues from normal priority queues are:[5]

Dual structure method

A dual structure with 14,12,4,10,8 as the members of DEPQ.[1]

In this method two different priority queues for min and max are maintained. The same elements in both the PQs are shown with the help of correspondence pointers.
Here, the minimum and maximum elements are values contained in the root nodes of min heap and max heap respectively.

  • Removing the min element: Perform removemin() on the min heap and remove(node value) on the max heap, where node value is the value in the corresponding node in the max heap.
  • Removing the max element: Perform removemax() on the max heap and remove(node value) on the min heap, where node value is the value in the corresponding node in the min heap.

Total correspondence

A total correspondence heap for the elements 3, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11 with element 11 as buffer.[1]

Half the elements are in the min PQ and the other half in the max PQ. Each element in the min PQ has a one-to-one correspondence with an element in max PQ. If the number of elements in the DEPQ is odd, one of the elements is retained in a buffer.[1] Priority of every element in the min PQ will be less than or equal to the corresponding element in the max PQ.

Leaf correspondence

A leaf correspondence heap for the same elements as above.[1]

In contrast to a total correspondence, in this method only the leaf elements of the min and max PQ form corresponding one-to-one pairs. It is not necessary for non-leaf elements to be in a one-to-one correspondence pair.[1] If the number of elements in the DEPQ is odd, one of the elements is retained in a buffer.[1]

Interval heaps

Implementing a DEPQ using interval heap.

Apart from the above-mentioned correspondence methods, DEPQ's can be obtained efficiently using interval heaps.[6] An interval heap is like an embedded min-max heap in which each node contains two elements. It is a complete binary tree in which:[6]

  • The left element is less than or equal to the right element.
  • Both the elements define a closed interval.
  • Interval represented by any node except the root is a sub-interval of the parent node.
  • Elements on the left hand side define a min heap.
  • Elements on the right hand side define a max heap.

Depending on the number of elements, two cases are possible[6] -

  1. Even number of elements: In this case, each node contains two elements say p and q, with p ≤ q. Every node is then represented by the interval [pq].
  2. Odd number of elements: In this case, each node except the last contains two elements represented by the interval [pq] whereas the last node will contain a single element and is represented by the interval [pp].

Inserting an element

Depending on the number of elements already present in the interval heap, following cases are possible:

  • Odd number of elements: If the number of elements in the interval heap is odd, the new element is firstly inserted in the last node. Then, it is successively compared with the previous node elements and tested to satisfy the criteria essential for an interval heap as stated above. In case if the element does not satisfy any of the criteria, it is moved from the last node to the root until all the conditions are satisfied.[6]
  • Even number of elements: If the number of elements is even, then for the insertion of a new element an additional node is created. If the element falls to the left of the parent interval, it is considered to be in the min heap and if the element falls to the right of the parent interval, it is considered in the max heap. Further, it is compared successively and moved from the last node to the root until all the conditions for interval heap are satisfied. If the element lies within the interval of the parent node itself, the process is stopped then and there itself and moving of elements does not take place.[6]

The time required for inserting an element depends on the number of movements required to meet all the conditions and is O(log n).

Deleting an element

  • Min element: In an interval heap, the minimum element is the element on the left hand side of the root node. This element is removed and returned. To fill in the vacancy created on the left hand side of the root node, an element from the last node is removed and reinserted into the root node. This element is then compared successively with all the left hand elements of the descending nodes and the process stops when all the conditions for an interval heap are satisfied. In case if the left hand side element in the node becomes greater than the right side element at any stage, the two elements are swapped[6] and then further comparisons are done. Finally, the root node will again contain the minimum element on the left hand side.
  • Max element: In an interval heap, the maximum element is the element on the right hand side of the root node. This element is removed and returned. To fill in the vacancy created on the right hand side of the root node, an element from the last node is removed and reinserted into the root node. Further comparisons are carried out on a similar basis as discussed above. Finally, the root node will again contain the max element on the right hand side.

Thus, with interval heaps, both the minimum and maximum elements can be removed efficiently traversing from root to leaf. Thus, a DEPQ can be obtained[6] from an interval heap where the elements of the interval heap are the priorities of elements in the DEPQ.

Time complexity

Interval heaps

When DEPQ's are implemented using Interval heaps consisting of n elements, the time complexities for the various functions are formulated in the table below[1]

Operation Time complexity
init() O(n)
isEmpty() O(1)
getmin() O(1)
getmax() O(1)
size() O(1)
insert(x) O(log n)
removeMin() O(log n)
removeMax() O(log n)

Pairing heaps

When DEPQ's are implemented using heaps or pairing heaps consisting of n elements, the time complexities for the various functions are formulated in the table below.[1] For pairing heaps, it is an amortized complexity.

Operation Time complexity
isEmpty() O(1)
getmin() O(1)
getmax() O(1)
insert(x) O(log n)
removeMax() O(log n)
removeMin() O(log n)

Applications

External sorting

One example application of the double-ended priority queue is external sorting. In an external sort, there are more elements than can be held in the computer's memory. The elements to be sorted are initially on a disk and the sorted sequence is to be left on the disk. The external quick sort is implemented using the DEPQ as follows:

  1. Read in as many elements as will fit into an internal DEPQ. The elements in the DEPQ will eventually be the middle group (pivot) of elements.
  2. Read in the remaining elements. If the next element is ≤ the smallest element in the DEPQ, output this next element as part of the left group. If the next element is ≥ the largest element in the DEPQ, output this next element as part of the right group. Otherwise, remove either the max or min element from the DEPQ (the choice may be made randomly or alternately); if the max element is removed, output it as part of the right group; otherwise, output the removed element as part of the left group; insert the newly input element into the DEPQ.
  3. Output the elements in the DEPQ, in sorted order, as the middle group.
  4. Sort the left and right groups recursively.

See also

References

  1. ^ a b c d e f g h i Data Structures, Algorithms, & Applications in Java: Double-Ended Priority Queues, Sartaj Sahni, 1999.
  2. ^ Brass, Peter (2008). Advanced Data Structures. Cambridge University Press. p. 211. ISBN 9780521880374.
  3. ^ "Depq - Double-Ended Priority Queue". Archived from the original on 2012-04-25. Retrieved 2011-10-04.
  4. ^ "depq".
  5. ^ Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni and Dinesh Mehta
  6. ^ a b c d e f g http://www.mhhe.com/engcs/compsci/sahni/enrich/c9/interval.pdf [bare URL PDF]

Read other articles:

8x8, 6x6, and 4x4 off-road trucks MAN Category 1 MAN Category 1 5,000 kg 4×4 cargo truck of the German Bundeswehr. When fitted with a winch, the Bundeswehr designation for this vehicle is Type 461 LKW 5t mil gl MW Pritsche, without a winch, the designation is Type 451 LKW 5t mil gl PritscheType8x8, 6x6, and 4x4 off-road trucksPlace of originWest GermanyService historyUsed byWest Germany, Belgium, France, Canada, Austria, USA, Estonia and probably othersProduction historyManufa...

 

Cet article est une ébauche concernant la guitare. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Un pickguard percé de trous de montage et son jeu de vis Le pickguard est une plaque, généralement en plastique, utilisée pour protéger la caisse des guitares des diverses rayures dues au plectre (aussi appelé médiator) et également des rayures d'ongles pour les guitaristes rythmiques. Pickguard (en noir) s...

 

Devolutionskrieg Einzug Ludwigs XIV. und Maria Theresia in Arras (Juli 1667) Datum 24. Mai 1667 – 2. Mai 1668 Ort Spanische Niederlande Ausgang Französischer Sieg Friedensschluss Friede von Aachen Konfliktparteien Frankreich Konigreich 1791 Frankreich Spanien 1506 SpanienSchweden SchwedenEngland Konigreich EnglandRepublik der Vereinigten Niederlande Vereinigte Niederlande Kriege Ludwigs XIV. (1667–1714) Devolutionskrieg – Holländischer Krieg – Reunionskrieg ...

Athletics at the Olympics Men's 2500 metres steeplechaseat the Games of the II OlympiadFinish of the raceVenueBois de BoulogneDateJuly 15Competitors6 from 6 nationsWinning time7:34.4Medalists George Orton Canada Sidney Robinson Great Britain Jean Chastanié France Athletics at the1900 Summer OlympicsTrack events60 mmen100 mmen200 mmen400 mmen800 mmen1500 mmen110 m hurdlesmen200 m hurdlesmen400 m hurdlesmen2500 m steeplechasemen4000 m steeplechasemen5000 m team racemen...

 

Taeniidae Taenia hydatigena Klasifikasi ilmiah Domain: Eukaryota Kerajaan: Animalia Filum: Platyhelminthes Kelas: Cestoda Ordo: Cyclophyllidea Famili: TaeniidaeLudwig, 1886 Genus Echinococcus Rudolphi, 1801 Hydatigera Lamarck, 1816 Taenia Linnaeus, 1758 Versteria Nakao, Lavikainen, Iwaki, Haukisalmi, Konyaev, Oku, Okamoto & Ito, 2013 [1] Taeniidae /tɪˈnaɪ.ɪdiː/ adalah sebuah keluarga cacing pita (Kelas Cestoda), dan merupakan keluarga terbesar dalam ordo Cyclophyllidea.[2...

 

2002 video gameIce AgeNorth American cover artDeveloper(s)Artificial Mind and MovementPublisher(s)Ubi SoftPlatform(s)Game Boy AdvanceReleaseNA: March 18, 2002EU: April 19, 2002JP: July 20, 2002Genre(s)Platform gameMode(s)Single-player Ice Age is a 2002 platform game based on the film of the same name, developed by Artificial Mind and Movement, published by Ubi Soft and released exclusively for the Game Boy Advance. A sequel, Ice Age 2: The Meltdown, was released on multiple platforms in 2006,...

Japanese special police force The censorship section of the Special Higher Police bureau of the Tokyo Metropolitan PD. The Special Higher Police (特別高等警察, Tokubetsu Kōtō Keisatsu), often abbreviated Tokkō (特高, Tokkō), was, from 1911 to 1945, a Japanese policing organization, established within the Home Ministry for the purpose of carrying out high policing, domestic criminal investigations, and control of political groups and ideologies deemed to threaten the public order o...

 

Selat Sepuluh Derajat adalah selat yang memisahkan Kepulauan Andaman dari Kepulauan Nikobar di Teluk Benggala. Dua kepulauan ini membentuk wilayah persatuan Kepulauan Andaman dan Nikobar di India. Selat ini memiliki luas sebesar 150 km persegi. Pranala luar http://www.traveljournals.net/explore/india/map/m2932784/ten_degree_channel.html Diarsipkan 2008-12-04 di Wayback Machine. Artikel bertopik geografi atau tempat India ini adalah sebuah rintisan. Anda dapat membantu Wikipedia dengan mengemb...

 

Ця стаття не містить посилань на джерела. Ви можете допомогти поліпшити цю статтю, додавши посилання на надійні (авторитетні) джерела. Матеріал без джерел може бути піддано сумніву та вилучено. (лютий 2023) Конституція Філіппін (філіппінська: Saligang Batas ng Pilipinas або Konstitusyon ng Pil...

此條目需要补充更多来源。 (2012年12月21日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能會因為异议提出而被移除。致使用者:请搜索一下条目的标题(来源搜索:FORCE原力誌 — 网页、新闻、书籍、学术、图像),以检查网络上是否存在该主题的更多可靠来源(判定指引)。 FORCE原力誌类别漫畫雜誌、輕小說雜誌发行周期週刊首发日期2012年12月20日公...

 

جبع   الإحداثيات 32°39′05″N 34°57′43″E / 32.65131944°N 34.96204167°E / 32.65131944; 34.96204167  تقسيم إداري  البلد فلسطين الانتدابية  التقسيم الأعلى قضاء حيفا  خصائص جغرافية  المساحة 7012 كيلومتر مربع  تعديل مصدري - تعديل   32°39′05″N 34°57′43″E / 32.65131944°N 34.96204167°E...

 

For the later diesel locomotives, see Victorian Railways C class (diesel). Victorian Railways C ClassVR photograph of C 1, as built in 1918.Type and originPower typesteamDesignerW. M. ShannonBuilderNewport WorkshopsBuild date1918–1926Total produced26SpecificationsConfiguration:​ • Whyte2-8-0 • UIC1'Dh2Gauge5 ft 3 in (1,600 mm)Leading dia.3 ft 1+7⁄16 in (0.951 m)Driver dia.5 ft 1+11⁄16 in (1.567 m)Le...

Faroese musician This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Teitur Lassen – news · newspapers · books · scholar · JSTOR (April 2020) (Learn how and when to remove this template message) Tei...

 

HarapanDesaKantor Kepala Desa HarapanNegara IndonesiaProvinsiSumatera UtaraKabupatenDairiKecamatanTanah PinemKode pos22253Kode Kemendagri12.11.06.2003 Luas... km²Jumlah penduduk... jiwaKepadatan... jiwa/km² Harapan merupakan salah satu desa yang ada di kecamatan Tanah Pinem, Kabupaten Dairi, provinsi Sumatera Utara, Indonesia. Pemerintahan Desa Harapan terdiri dari Dusun Kuta Mbaru Atas, Kuta Mbaru Bawah, Kuta Mbaru Impres, Lau Meciho I, Lau Meciho II, Lau Meciho III. Galeri Gereja GBK...

 

1981 video game This article is about the 1980s Stargate video game. For the game based on the film, see Stargate (1995 video game). For other uses, see Stargate (disambiguation). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Stargate 1981 video game – news · newspapers · books · scholar · JSTOR (July...

A magic graph is a graph whose edges are labelled by the first q positive integers, where q is the number of edges, so that the sum over the edges incident with any vertex is the same, independent of the choice of vertex; or it is a graph that has such a labelling. The name magic sometimes means that the integers are any positive integers; then the graph and the labelling using the first q positive integers are called supermagic. A graph is vertex-magic if its vertices can be labelled so that...

 

Type of diagrammatic or visual notation for logical expressions You can help expand this article with text translated from the corresponding article in German. (May 2017) Click [show] for important translation instructions. View a machine-translated version of the German article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply ...

 

Annual contest held in Petaluma, California, US A 2013 contestant The World's Ugliest Dog Contest is an annual contest held in Petaluma, California, as part of the Sonoma-Marin Fair, to decide which of the dogs entered in the contest is the ugliest. The contest, along with the rest of the fair, is typically scheduled for the fourth week of June. Along with the title of “The World’s Ugliest Dog” the winner’s owner receives a check for $1,000 and a trophy[1] As of 2017, the priz...

Disambiguazione – Se stai cercando il film del 1973, vedi Un magnifico ceffo da galera. Nella storia degli Stati Uniti, scalawag[1] era il soprannome dato ai bianchi del sud che sostennero la ricostruzione dopo la Guerra di secessione. Indice 1 Origini del termine 2 Cronologia 3 Le accuse di corruzione 4 Influenza 5 Scalawags noti 6 Note 7 Bibliografia 8 Voci correlate 9 Altri progetti Origini del termine Il termine era in origine un epiteto dispregiativo (originariamente significav...

 

1978 Hong Kong filmInvincible ShaolinChinese nameTraditional Chinese南少林與北少林Simplified Chinese南少林与北少林TranscriptionsStandard MandarinHanyu PinyinNán Shàolín Yǔ Běi ShàolínYue: CantoneseJyutpingNaam4 Siu2 Lam4 Jyu5 Bak1 Siu2 Lam4 Directed byChang ChehWritten byChang ChehNi KuangProduced bySir Run Run ShawStarringLu FengSun ChienChiang ShengWai PakKuo ChuiLo MangCinematographyCho Wai-KeiEdited byChiang Hsing-LungMusic byFrankie ChanProductioncompanyShaw Bro...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!