0
arr = [7, 3, 5, 6, 7, 1, 8, 0, 4, 9, 6, 2]
def partitioning(arr, l, d):
    pivot = 5
    while l <= d:
        while arr[l] < pivot:
            l += 1
        while arr[d] > pivot:
            d -= 1
        arr[l], arr[d] = arr[d], arr[l]
partitioning(arr, 0, len(arr) - 1)
print(arr)

I don't understand why when putting l <= d, when l and d become the same they stop moving and keep swapping to infinity?

1
  • Did you "execute" this program step by step, using either your favourite debugger or just pen and paper? Commented Feb 2, 2016 at 19:37

1 Answer 1

2

Your infinite loop happens when l == d and arr[l] == arr[d] == pivot. In this situation, the inner loops never do anything and the swap also doesn't do anything since the two indexes are the same (so you're swapping the pivot with itself).

You want your top loop to quit in this situation, since the array has been completely partitioned. You should change the <= on the outer loop to <, and it should work.

You'll need to change the pivot-choice logic going forward (since if the pivot is not in the list, your inner loops might run l or d off the end of the list), but I assume that picking the constant 5 is just a preliminary thing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.