I'm trying to make a divide-and-conquer approach that points out the first number in a list that does not follow a n+1 sequence. And if all of them do follow the sequence, return -1.
So for example, if I have an array of numbers of size 8:
int size = 9;
int listofNumbers[9] = { 4, 5, 6, 7, 8, 9, 3, 6, 7 };
I would need a function that scans the array and returns 3, since it's the first one that fails to meet the n+1 sequence.
I made an approach using iteration, and it works:
int findFirst_iterative(int list[], int listSize)
{
if (listSize < 1)
{
return -1; // empty list.
}
int nextNumber = list[0]; // we start with the first number in the list.
for (int i = 1; i < listSize; i++)
{
if (list[i] != (nextNumber + 1))
{
return list[i];
}
nextNumber = list[i];
}
return -1;
}
I am now trying to do the same but using a divide-and-conquer approach.
int findFirst_divideandconquer(int list[], int listSize)
{
if (listSize < 1)
{
return -1; // the list is empty.
}
else if (listSize == 2)
{
if (list[1] != list[0] + 1)
{
return list[1];
}
else
{
return -1;
}
}
int mid = listSize / 2;
int listhalfA[mid];
int listhalfB[mid];
int overallindex = 0;
for (int i = 0; i < mid; i++)
{
listhalfA[i] = list[overallindex];
overallindex = overallindex + 1;
}
for (int i = 0; i < mid; i++)
{
listhalfB[i] = list[overallindex];
overallindex = overallindex + 1;
}
int resultA = findFirst_divideandconquer(listhalfA, mid);
if (resultA == -1)
{
int resultB = findFirst_divideandconquer(listhalfB, mid);
if (resultB == -1)
{
return -1;
}
return resultB;
}
return resultA;
}
I've hit a roadblock, while I succeeded in dividing the list in halves, it will return the second number that fails to meet the sequence, instead of the first one. So the code above returns 6 instead of 3, which is what I need.
How could I fix this?
int mid = listSize / 2; int listhalfA[mid]; int listhalfB[mid];This won't work for odd sized arrays as it will miss one element - which is the case in the code shown. For odd sized arrays one half will have one more element than the other half.int listhalfB[mid];, useint listhalfB[listSize - mid];.