Write a recursive function that inserts an element e in a stack and keeps it sorted. The top element is the smallest one.


Difficulty level
This exercise is mostly suitable for students
int add_sorted(stack *s, element e)
{
	element e1;
	if(isEmptyStack(*s) || (!isEmptyStack(*s) && Top(*s,&e1) && e1>e))
	{
		Push(s,e);
		return 1;
	}
	else
		if(!isEmptyStack(*s) && Top(*s,&e1) && e1<e)
		{
			Pop(s);
			if(!add_sorted(s, e)) return 0;
			Push(s,e1);
			return 1;
		}
	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sum of odd numbers in a range of integers using recursion