Partitioning Arrays
The Partition algorithm for an array uses one of its elements, called a pivot, and returns a permutation of the array where the elements to the left of its position in the response are all smaller than it and the elements to the right are all greater than or equal to it Additionally, the function returns the new position of the pivot element.
For example, given the array below:
A
And using the last element as the pivot, a possible solution could be:
A
With the pivot index equal to
Note that the algorithm's definition does not specify that the relative order of the original elements should be preserved eg Element was before and
If the following C code is provided, implementing a version of the algorithm:sizet partitionint a int n
Get pivot element
int pivot an ;
Create two temp arrays to hold smaller and larger elements than pivot
int smaller mallocsizeofint n;
int larger mallocsizeofint n;
Init arrays insertion indexes
sizet smalleridx ;
sizet largeridx ;
sizet idx;
Iterate over all elements and copy to corresponding array
for sizet idx ; idx n ; idx
Check element smaller than pivot
if aidx pivot
Copy to smaller array
smallersmalleridx aidx;
else
Copy to larger array
largerlargeridx aidx;
Set pivot index
sizet pivotidx smalleridx;
Insert smaller elements to original array
for idx ; idx pivotidx; idx
aidx smalleridx;
Copy pivot to correct position
apivotidx pivot;
Insert larger elements to original array
for idx ; idx pivotidx; idx
apivotidx idx largeridx;
Free temp arrays
freesmaller;
freelarger;
Return pivot index
return pivotidx;
Requested:
a Find the asymptotic runtime for the algorithm. Assume malloc and free run in O
b The time for malloc and free is implementationdependent. Assuming now the times for these operations are On does this affect the asymptotic runtime of the algorithm?