This code finds if in a sorted array there are three numbers that add up to a given sum, but I'm not sure how to calculate its time complexity. Would love your input and ideas on how to improve it as well.
Note that the for
loop can reset itself within the loop.
/* function to find if there are 3 values in the
sorted array that sum up to a given sum */
int IsSumOf3( int arr[], size_t size, int sum)
{
int right, left, third;
right = size-1;
left = 0;
while(arr[right] > sum && right > 1)
{
--right;
}
if(right == 1)
{
printf("returned false on right == 1 \n");
return 0;
}
for(third = left+1; third < right; ++third)
{
int localSum = arr[right]+ arr[left]+ arr[third];
if(localSum == sum)
{
printf("right |%d|, left |%d|, third |%d|\n",arr[right], arr[left], arr[third]);
return 1;
}
if(localSum > sum)
{
--right;
left = 0;
third = left;
}
if(third+1 == right)
{
++left;
third = left;
}
}
printf("returned false on exit\n");
return 0;
}
int main()
{
int A[] = { 1, 4, 6, 8, 10, 46 };
IsSumOf3(A,6, 22);
IsSumOf3(A,6, 11);
IsSumOf3(A,6, 100);
IsSumOf3(A,6, 3);
return 0 ;
}