awangdev / leet-code

Java Solutions to problems on LintCode/LeetCode

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Partition Array is buggy

asarkar opened this issue · comments

https://github.com/awangdev/LintCode/blob/master/Java/Partition%20Array.java#L54 won't work for [9, 4, 1, 8, 5, 10, 6, 3, 7, 2], pivot = 7

Iteration 1:
low = 0
high = 9
swap(0,9) -> [2, 4, 1, 8, 5, 10, 6, 3, 7, 9]

Iteration 2:
low = 3
high = 7
swap(3,7) -> [2, 4, 1, 3, 5, 10, 6, 8, 7, 9]

Iteration 3:
low = 5
high = 6
swap(5,6) -> [2, 4, 1, 3, 5, 6, 10, 8, 7, 9]

Iteration 4:
low = 6
high =5

Array is not partitioned, returns 6.

The 4 iterations are accurate, and eventually low++ will result to be 6, which points to value 10.
10 is the first value >= k.
What you commented is working perfectly as expected.

Isn’t the purpose of partitioning to return the final position of the pivot, which is value 7 in the example above?

check the requirement: Return the partitioning index, i.e the first index i nums[i] >= k.. In this case, it'll be index 6, value 10.