Skip to content

Instantly share code, notes, and snippets.

@xoposhiy
Last active December 19, 2015 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xoposhiy/5950893 to your computer and use it in GitHub Desktop.
Save xoposhiy/5950893 to your computer and use it in GitHub Desktop.
А вам слабо найти тест, на котором эта штука не работает? :-)
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestingTask
{
public class Heap<T>
{
private readonly List<T> data = new List<T>(10);
private readonly Func<T, int> score;
public Heap(Func<T, int> score)
{
this.score = score;
}
public int Count
{
get { return data.Count; }
}
public T PeekBest()
{
if (Count == 0) throw new InvalidOperationException("Heap is empty");
return data[0];
}
public T ExtractBest()
{
if (Count == 0) throw new InvalidOperationException("Heap is empty");
T res = data[0];
data[0] = data[data.Count - 1];
data.RemoveAt(data.Count - 1);
Down(0);
return res;
}
public void Add(T item)
{
data.Add(item);
Up(data.Count - 1);
}
private void Up(int i)
{
if (i == 0) return;
int parent = i/2;
if (score(data[parent]) < score(data[i]))
{
Swap(parent, i);
Up(parent);
}
}
private void Swap(int j, int i)
{
T t = data[j];
data[j] = data[i];
data[i] = t;
}
private void Down(int i)
{
int c1 = i*2;
int c2 = i*2 + 1;
if (c1 >= data.Count) return; // уже на дне!
int c = (c2 < data.Count && score(data[c2]) > score(data[c1])) ? c2 : c1;
if (score(data[i]) < score(data[c]))
{
Swap(i, c);
Down(c);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment