Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
the program is supposed to be a recursive function to check ascendingly sorted array
here's my trial but the program doesn't run well it's supposed to print 1 ,instead, it prints -1!

What I have tried:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int iss(int list[],int size)
{
    if(*list > *(list+1)) return -1;
    if(list==list+size-1) return 1;
    return iss(list+1,size);
}

int main()
{ int arr[5]={1,1,5,6,7};
printf("%d",iss(arr,5));
return 0;
}
Posted
Updated 4-Nov-17 11:39am
Comments
PIEBALDconsult 4-Nov-17 15:53pm    
For that task; iterate, don't recurse.
And if you know it's sorted, then try a binary search.

1 solution

The following stop condition
Quote:
f(list==list+size-1) return 1;
is flawed: if, at first iss call, (size > 1) then it can be never satisfied.
Try instead
C
int iss(int list[],int size)
{
    if ( size == 0 ) return 1;
    if(*list > *(list+1)) return -1;
    return iss(list+1,size-1);
}
 
Share this answer
 
Comments
Member 13476370 5-Nov-17 0:02am    
I understand your solution and it's surely better than mine ... but I still don't know why can't if(list==list+size-1) be satisfied? ... every time I change the pointer arithmetically to the next element then The last pointer points at last element of the array ... why isn't that supposed to work?
CPallini 5-Nov-17 6:07am    
Think about:
list == list + size - 1
on the left and right side of the expression the value of list is always the same, hence the whole expression is equivalent to
0 == size - 1
since size doesn't change, if at first call (size > 1) then the result of the expression can never be true.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900