Question

PYTHON QUESTION Given the following function: def sort(A, n):     for i in range (1, n):...

PYTHON QUESTION

Given the following function:

def sort(A, n):

    for i in range (1, n):

        for j in range(i-1, -1,-1):

            if A[j + 1] > A[j]:

                t = A[j+1]

                A[j+1] = A[j

                A[j] = t

What would the output be for the following array: A = [3, 10, 2, 8,15]; where n = 5; for each iteration of i (i.e. when i = 1, i=2, i=3, i=4)?

A. 10, 3, 2, 8, 15

B. 10, 8, 3, 2, 15

C. 15, 10, 8, 3, 2

Match i=1, i=2, i=3 and i=4 to the letters A, B, or C

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

The code snippet you have provided is reverse sorting the array.

In the ith iteration we are reverse sorting the array till index i by placing the larger element in the starting. Inner loop is used to pick that larger element by comparing it with all previous elements..

So array state after iteration 1 - [10, 3, 2, 8, 15] - A

array state after iteration 2 - [10, 3, 2, 8, 15] - A

array state after iteration 3- [10, 8, 3, 2, 15] - B

array state after iteration 4 - [15, 10, 8, 3, 2] - C

You could try and run the following code to see the output by yourself : -

def sort(A, n):
    for i in range(1, n):

        for j in range(i - 1, -1, -1):

            if A[j + 1] > A[j]:
                t = A[j + 1]

                A[j + 1] = A[j]

                A[j] = t
        print(A)
    return A


if __name__ == '__main__':
    print(sort([3,10,2,8,15],5))

If you have any doubt or want any clarification just put a comment on the answer.

Add a comment
Know the answer?
Add Answer to:
PYTHON QUESTION Given the following function: def sort(A, n):     for i in range (1, n):...
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