Question

[python] Write a method that given a heap array returns the second smallest element in a...

[python] Write a method that given a heap array returns the second smallest element in a heap.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import sys

  

def print2Smallest(arr):

  

    # There should be atleast two elements

    arr_size = len(arr)

    if arr_size < 2:

        print "Invalid Input"

        return

  

    first = second = sys.maxint

    for i in range(0, arr_size):

  

        # If current element is smaller than first then

        # update both first and second

        if arr[i] < first:

            second = first

            first = arr[i]

  

        # If arr[i] is in between first and second then

        # update second

        elif (arr[i] < second and arr[i] != first):

            second = arr[i];

  

    if (second == sys.maxint):

        print "No second smallest element"

    else:

        print ' second smallest element is',second

  

arr = [12, 13, 1, 10, 34, 1]

print2Smallest(arr)

The above code is efficient in finding the second smallest element and the first smallest element in the heap array.

Can also be done using extract-min for the heap 2 times. it will take o(1) time.

Add a comment
Know the answer?
Add Answer to:
[python] Write a method that given a heap array returns the second smallest element in a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT