Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7491311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T15:57:48+00:00 2026-05-29T15:57:48+00:00

I created a BinaryHeap<T> class. public class BinaryHeap<T> { private List<T> _heap; // Constructor

  • 0

I created a BinaryHeap<T> class.

public class BinaryHeap<T>
{
    private List<T> _heap;

    // Constructor
    public BinaryHeap(int capacity, IComparer<T> comparer)
    {
        this._heap = new List<T>(capacity);
        Comparer = comparer ?? Comparer<T>.Default;
    }

    // Constructor
    public BinaryHeap(int capacity) : this(capacity, (IComparer<T>)null) { }

    // Gets/sets IComparer
    public IComparer<T> Comparer { get; private set; }

    // Gets/sets the capacity
    public int Capacity
    {
        get { return this._heap.Capacity; }
        set { this._heap.Capacity = value; }
    }

    // Gets the number of elements
    public int Count
    {
        get { return this._heap.Count; }
    }

    // Inserts the specified element within this BinaryHeap.
    public void Insert(T element)
    {
        // Add the element as the last element.
        this._heap.Add(element);

        // Index of last added element.
        int last = this._heap.Count - 1;

        int parent;
        T swap;
        while (last > 0)
        {
            parent = (last - 1) >> 1;   // parent(i) = (i-1)/2

            if (Comparer.Compare(this._heap[parent], this._heap[last]) <= 0)
                break;   // exit while if the current node is lesser than its parent.

            swap = this._heap[last];                // If the parent is greater
            this._heap[last] = this._heap[parent];  // than the current node,
            this._heap[parent] = swap;              // then swap them.

            last = parent;   // Updates index of last added element.
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public T Remove()
    {
        if (this._heap.Count > 0)
        {
            // Save the element.
            T result = this._heap[0];

            int lastIndex = this._heap.Count - 1;   // The last element moves
            this._heap[0] = this._heap[lastIndex];  // moves to the root
            this._heap.RemoveAt(lastIndex);         // of this tree.
            lastIndex--;   // Update position of last element.

            int i = 0;   // Position of moved node.
            while (i < lastIndex)
            {
                int minIndex = i;

                int left = (i << 1) + 1;   // left(i) = (i*2)+1
                if (left < lastIndex && Comparer.Compare(this._heap[left], this._heap[minIndex]) < 0)
                {
                    minIndex = left;
                }

                int right = left + 1;   // right(i) = (i*2)+2
                if (right < lastIndex && Comparer.Compare(this._heap[right], this._heap[minIndex]) < 0)
                {
                    minIndex = right;
                }

                if (minIndex != i)
                {
                    // If one of the two children is lesser than the parent,
                    // then swap the latter with the lesser child.
                    T temp = this._heap[i];
                    this._heap[i] = this._heap[minIndex];
                    this._heap[minIndex] = temp;
                    i = minIndex;
                }
                else break;
            }

            // Return the minimum element that has been removed.
            return result;
        }
        else throw new InvalidOperationException("BinaryHeap is empty.");
    }
}

In performed some test, for example the following test as simple queue.

BinaryHeap<int> q = new BinaryHeap<int>(0);
int count = 50;
for (int i = 0; i < count; i++)
    q.Insert(i);
for (int i = 0; i < count; i++)
    Console.WriteLine(q.Remove());
Console.ReadLine();

The returned elements should be in ascending order, but the third-last element and the penultimate element are almost always in wrong order. For example, with count = 50, the output is:

// previous element are in correct order
44
45
46
48   // wrong order
47   // wrong order
49

Testing several count values, this problem does not always occur.
Why?
How can I resolve this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T15:57:50+00:00Added an answer on May 29, 2026 at 3:57 pm

    The symptom indicates a problem in the Remove() method.

    Your lastIndex var is pointing at the last item, so in the 2 calculations of minIndex you should use <=

     // if (left < lastIndex && ...)
        if (left <= lastIndex && ...)
    

    and the same for right.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i created web project, and added new class library for framework. This framework includes
Created a new App, created a new Fanpage for this App but if i
I created a single page (with code behind .vb) and created Public intFileID As
I created a Rails application normally. Then created the scaffold for an event class.
I created a list of lists: >>> xs = [[1] * 4] * 3
I created a new SharePoint portal for testing purposes using a manually added HOSTS
created a new IIS7 web site with Intergrated .net 4.0 app pool. URLs ending
Created new scaffold Users that has fields name & description All working as suppose
I created the following simple class in my code and I get TObject is
I created a new MVC3 project, hit F5, saw the sample page. Then I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.