Difference between Max Heap and Sorted Stack

I want to know that when we can sort the stack using the Collections.sort method, why do we need a new data structure like max heap? thanks

+3
source share
3 answers

Stack and heap have completely different properties and customs.

The stack is necessary for LIFO. Sorting will cost O (N * logN), Push / pop O (1).

A heap is needed for the priority queue, for example, to get the min / max element it will cost O (1), inserting the O (log (N)) element

You need to define a usage pattern and purpose, and then decide what exactly you need.

+6
source

Collections.sort O (n log n). , Collections.sort , . O (log n).

. , . , , (, ) .

+1

. Stack and Heap . , . - O (nlog (n)), (Max/Min) O (log (n)) .

So, your question is where to use MaxHeap, think of a scenario where you need to find the 7th largest element out of 1000. First you need to sort on the stack, and then the seventh from the beginning (sorting in descending order) will be a solution, but using MaxHeap you have to extract the item 7 times and the 7th will be the solution. So your scenario depends on which one might be best for you.

0
source

Source: https://habr.com/ru/post/1749789/


All Articles