Given a randomly ordered array of n
elements partition the elements into two subsets such that elements less than x
are in one subset and elements greater than x
are in separate subset. For instance, [28, 26, 25, 11, 16, 12, 24, 29, 6, 10]
and x = 17
lead to the array [10, 6, 12, 11, 16, 25, 24, 29, 26, 28]
.
I thought of an algorithm as follows:
Establish the array
a[0,...,n]
and the partitioning valuex
.Move the partitions towards each other until the wrongly placed elements are encountered. Allow for special cases such as
x
being outside the range of array values.While the two partitions have not crossed over exchange the wrongly partitioned pair and extend both partitions inward by one element
extend left partition while elements less than or equal to
x
extend the right partition while elements are greater than
x
Return the partitioning index
p
in the partitioned array.