I'm writing a function that gets an array of int and its size:
void partition(int data[], int size)
The first element of the array is assigned to a variable named val, and the function needs to partition the array such that elements to the left of val are smaller than val, and elements to the right are greater.
For example,
if the array is :
5 2 10 4 1 12 7(valbecomes5)The output should be
2 4 1 5 10 12 7
The order doesn't matter so 1 2 4 5 12 7 10 is also valid output
So I wrote this code:
void partition(int data[], int size)
{
int val = data[0];
int i = 0, j = size - 1;//array indices
while (i != j)
{
while (data[i] < val)
i++;
while (data[j] > val)
j--;
swapInArray(data, i, j);
}
}
which works fine unless it gets an array with elements equivalent to val.
For example : 7 8 5 176 18 19 7 12 44
while (data[i] <= val)instead ofwhile (data[i] < val)should do it.while (i != j)instead ofwhile (i < j).