×

# 2nd largest element of a max-heap

 0 Hai i have just started learning Data Structures.Please help me... Suppose i have a max heap of arr[1....n].arr[1] stores the maximum element. Is there any way in which i can find the second largest element in the array. we are not supposed to change the heap asked 29 Mar '14, 23:54 3★bipin2 3.1k●25●46●71 accept rate: 8%

 5 The max-heap is a tree structure in which the root contains the maximum element and value of each node is greater than the value of its children. The max-heap is stored as an array. So as the first element or the first index stores the maximum element of the max-heap. The second largest element of the heap is either of the two children of the max node i.e. either node 2 or node 3. Check the one which is bigger. answered 30 Mar '14, 00:11 1.5k●1●10●25 accept rate: 23% Thanks a lot!! (30 Mar '14, 22:01) bipin23★ 1 @bipin2 Your welcome! Please accept the solution if you are satisfied so that the question could be closed. (31 Mar '14, 14:02) Sorry....I forget that..:) (01 Apr '14, 19:14) bipin23★
 0 If you are using a priority_queue , this can be done very easily. Pop from priority_queue and store it in a temp variable.(This the largest element in the heap). Pop again from the queue which will be the second largest of the max_heap. Push again the temp variable into the heap, so that the heap remains in its initial state and only the second most largest element is removed from the heap. If you need more clarifications just leave a comment below. answered 30 Mar '14, 00:24 151●4●11 accept rate: 25% thanks....but i wanted to the array to remain the same....or we can take 2 temporary variables and the pop and pop and then push back the 2 temporary variables right? (30 Mar '14, 22:03) bipin23★ @bipin2 Yes you can do that. (01 Apr '14, 00:29)
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×1,310
×461
×288
×42

question asked: 29 Mar '14, 23:54

question was seen: 6,659 times

last updated: 01 Apr '14, 19:14