Created
July 22, 2020 08:23
-
-
Save fujieda/da6a752b13a261bcf37f40e7b7d5b4f6 to your computer and use it in GitHub Desktop.
Priority Queue for C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2020 Kazuhiro Fujieda | |
// | |
// Permission to use, copy, modify, and/or distribute this software for any | |
// purpose with or without fee is hereby granted. | |
// | |
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | |
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | |
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | |
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | |
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | |
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | |
// PERFORMANCE OF THIS SOFTWARE. | |
using System; | |
using System.Collections.Generic; | |
public class PriorityQueue<T> where T : IComparable<T> | |
{ | |
private readonly List<T> _array = new List<T>(); | |
private readonly int _order; | |
public PriorityQueue(bool min = false) | |
{ | |
_order = min ? -1 : 1; | |
} | |
public int Count => _array.Count; | |
public void Push(T item) | |
{ | |
var child = _array.Count; | |
_array.Add(item); | |
while (child > 0) | |
{ | |
var parent = (child - 1) / 2; | |
if (_order * _array[child].CompareTo(_array[parent]) > 0) | |
Swap(child, parent); | |
child = parent; | |
} | |
} | |
public T Pop() | |
{ | |
var last = _array.Count - 1; | |
var r = _array[0]; | |
_array[0] = _array[last]; | |
_array.RemoveAt(last); | |
last--; | |
for (int child = 1, parent = 0; child <= last; child = 2 * parent + 1) | |
{ | |
var left = child; | |
var right = child + 1; | |
if (right <= last && _order * _array[right].CompareTo(_array[left]) > 0) | |
child = right; | |
if (_order * _array[child].CompareTo(_array[parent]) > 0) | |
Swap(parent, child); | |
parent = child; | |
} | |
return r; | |
} | |
private void Swap(int i, int j) | |
{ | |
var tmp = _array[j]; | |
_array[j] = _array[i]; | |
_array[i] = tmp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment