Created
June 25, 2018 03:51
-
-
Save Emiton/bb65674f0da97be69f3dc5bcae8299f5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace HeapImplementation | |
| { | |
| public class MinHeap<T> where T : IComparable | |
| { | |
| private List<T> data = new List<T>(); | |
| public void Insert (T element) | |
| { | |
| data.Add(element); | |
| HeapifyUp(data.Count - 1); | |
| } | |
| public T Peek() | |
| { | |
| return data[0]; | |
| } | |
| private void HeapifyUp(int index) | |
| { | |
| while (index > 0) | |
| { | |
| int j = (index + 1) / 2 - 1; | |
| T dataChecker = data[j]; | |
| if (dataChecker.CompareTo(data[index]) <= 0) | |
| { | |
| break; | |
| } | |
| T switcher = data[index]; | |
| data[index] = data[j]; | |
| data[j] = switcher; | |
| index = j; | |
| } | |
| } | |
| public T GetMin() | |
| { | |
| T minVal = data[0]; | |
| data[0] = data[data.Count - 1]; | |
| data.RemoveAt(data.Count - 1); | |
| this.HeapifyDown(0); | |
| return minVal; | |
| } | |
| public void HeapifyDown(int index) | |
| { | |
| int min; | |
| int left = GetLeft(index); | |
| int right = GetRight(index); | |
| if (left < data.Count && (data[left].CompareTo(data[index])< 0)) | |
| { | |
| min = left; | |
| } | |
| else | |
| { | |
| min = index; | |
| } | |
| if (right < data.Count && (data[right].CompareTo(data[min]) < 0)) | |
| { | |
| min = right; | |
| } | |
| if (min != index) | |
| { | |
| T switcher = data[index]; | |
| data[index] = data[min]; | |
| data[min] = switcher; | |
| this.HeapifyDown(min); | |
| } | |
| } | |
| public int GetLeft(int index) | |
| { | |
| return 2 * index + 1; | |
| } | |
| public int GetRight(int index) | |
| { | |
| return 2 * index + 2; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment