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

  • Home
  • SEARCH
  • 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 6573809
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T15:10:50+00:00 2026-05-25T15:10:50+00:00

While iterating through a dataset, what’s the best way to keep track of only

  • 0

While iterating through a dataset, what’s the best way to keep track of only the top 10 numbers so far, in sorted order?

Solution…Ended up implementing Generic Min and Max Heaps…as sadly they are not available in Java libraries or readily on the internet….No gauruntees on the code…

import java.util.ArrayList;

public class MaxHeapGeneric <K extends Comparable> {
    //ArrayList to hold the heap
    ArrayList<K> h = new ArrayList<K>();
    public MaxHeapGeneric()
    {

    }
    public int getSize()
    {
        return h.size();
    }

    private K get(int key){
        return h.get(key);
    }


    public void add(K key){
        h.add(null);
        int k = h.size() - 1;
        while (k > 0){
            int parent = (k-1)/2;
            K parentValue = h.get(parent);
            //MaxHeap -
            //for minheap - if(key > parentValue)
            if(key.compareTo(parentValue) <= 0) break;
            h.set(k, parentValue);
            k = parent;
        }
        h.set(k, key);
    }
    public K getMax()
    {
        return h.get(0);
    }
    public void percolateUp(int k, K key){
        if(h.isEmpty())
            return ;

        while(k < h.size() /2){
            int child = 2*k + 1; //left child
            if(   child < h.size() -1 && (h.get(child).compareTo(h.get(child+1)) < 0)   )
            {
                child++;
            }

            if(key.compareTo(h.get(child)) >=0) break;

            h.set(k, h.get(child));
            k = child;
        }
        h.set(k, key);
    }
    public K remove()
    {
        K removeNode = h.get(0);
        K lastNode = h.remove(h.size() - 1);
        percolateUp(0, lastNode);
        return removeNode;
    }
    public boolean isEmpty()
    {
        return h.isEmpty();
    }

    public static void main(String[] args)
    {
        MaxHeapGeneric<Integer> test = new MaxHeapGeneric<Integer>();

        test.add(5);
        test.add(9);
        test.add(445);
        test.add(1);
        test.add(534);
        test.add(23);

        while(!test.isEmpty())
        {
            System.out.println(test.remove());
        }

    }

}

And a min heap

import java.util.ArrayList;


public class MinHeapGeneric <K extends Comparable> {
    //ArrayList to hold the heap
    ArrayList<K> h = new ArrayList<K>();
    public MinHeapGeneric()
    {

    }
    public int getSize()
    {
        return h.size();
    }

    private K get(int key){
        return h.get(key);
    }


    public void add(K key){
        h.add(null);
        int k = h.size() - 1;
        while (k > 0){
            int parent = (k-1)/2;
            K parentValue = h.get(parent);
            //for minheap - if(key > parentValue)
            if(key.compareTo(parentValue) > 0) break;
            h.set(k, parentValue);
            k = parent;
        }
        h.set(k, key);
    }
    public K getMax()
    {
        return h.get(0);
    }
    public void percolateUp(int k, K key){
        if(h.isEmpty())
            return ;

        while(k < h.size() /2){
            int child = 2*k + 1; //left child
            if(   child < h.size() -1 && (h.get(child).compareTo(h.get(child+1)) >= 0)   )
            {
                child++;
            }

            if(key.compareTo(h.get(child)) < 0) break;

            h.set(k, h.get(child));
            k = child;
        }
        h.set(k, key);
    }
    public K remove()
    {
        K removeNode = h.get(0);
        K lastNode = h.remove(h.size() - 1);
        percolateUp(0, lastNode);
        return removeNode;
    }
    public boolean isEmpty()
    {
        return h.isEmpty();
    }

    public static void main(String[] args)
    {
        MinHeapGeneric<Integer> test = new MinHeapGeneric<Integer>();

        test.add(5);
        test.add(9);
        test.add(445);
        test.add(1);
        test.add(534);
        test.add(23);

        while(!test.isEmpty())
        {
            System.out.println(test.remove());
        }

    }

}
  • 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-25T15:10:50+00:00Added an answer on May 25, 2026 at 3:10 pm

    Use a min-heap (priority queue) to keep track of the top 10 items. With a binary heap, the time complexity is O(N log M), where N is the number of items and M is 10.

    Compared to storing the top items in an array, this is faster for large M: array-based approach is O(NM). Ditto for linked lists.

    In pseudocode:

    heap = empty min-heap
    for each datum d:
        heap.push(d)   // add the new element onto the heap
        if heap.size > 10:
            heap.pop() // remove the smallest element
        endif
    endfor
    

    Now heap contains 10 largest items. To pop:

    while heap is not empty:
        item = heap.top()
        print item
    endwhile
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What's a better way to traverse an array while iterating through another array? For
According to Best way to remove from NSMutableArray while iterating? , we can't remove
Duplicate Modifying A Collection While Iterating Through It Has anyone a nice pattern to
What is the proper way to remove elements from a C++ vector while iterating
I have an associative array and while iterating through this array, using foreach loop.
I am having an issue removing elements of a list while iterating through the
When I am iterating through m_itFileBuffer stringlist container, I get an exception while fetching
While iterating through a std::map or std::vector or any container which has iterator in
Possible Duplicate: for vs foreach vs while which is faster for iterating through arrays
While iterating through an object containing data I'm checking if the url of image

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.