Given an 'N' number of elements, Find the Smallest Two numbers in a given array.
Implementation:
Implementation:
#include <stdio.h>
#include <stdlib.h>
/* Array size*/
#define MAX 1000000
/* Structure of Stack */
struct stack
{
/* To mark the top index of the stack */
int top;
/* To store the items of the stack using array */
int items[100];
};
/* Function to check whether the stack is empty */
int isempty(struct stack *s)
{
/* Check whether the index top points to -1, if yes return 1 or else return 0 */
return s->top==-1?1:0;
}
/* Function push to push data in to the stack */
void push(struct stack *s,int data)
{
/* Increment the top index */
s->top++;
/* Insert the data in the incremented top index */
s->items[s->top]=data;
}
/* Function printstack to print the elements of the stack */
void printstack(struct stack *s)
{
/* Assignming top index to a temporary variable, so that index top is unchanged */
int i=s->top;
/* Traverse through the stack and print all the elements until i becomes -1 */
for(;i>=0;i--)
printf("%d ",s->items[i]);
}
/* Function pop() to delete the element at the top of the stack and return the deleted element */
int pop(struct stack *s)
{
int d;
/* Store the top of the element in d */
d=s->items[s->top];
/* Decrement the top position */
s->top=s->top-1;
/* Return the deleted element */
return d;
}
/* Function smallest () to find the smallest element which is the top of the stack */
int smallest(struct stack *s)
{
int d;
/* Top of the stack is the smallest element */
d=pop(s);
/* To remove the elements in the top of the stack until we find second smallest element */
while(d==s->items[s->top] && !(isempty(s)))
pop(s);
/* Return the smallest element */
return d;
}
/* Function printarray() to print the array */
void printarray(int *a,int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",*(a+i));
}
int main(void) {
/* structure stack object which is used to access the member variables in the stack top, items[] */
struct stack s;
int n,a[MAX],i;
/* initialize the top index of the stack to -1, denotes the stack is empty */
s.top=-1;
/* Get the number of elements of the array */
scanf("%d",&n);
for(i=0;i<n;i++)
{
/* Get the elements of the array from the user */
scanf("%d",(a+i));
/* Insert the first element of the array into the stack */
if(isempty(&s))
push(&s,*(a+i));
/* Push the remaining elements of the array into the stack */
else if(!(isempty(&s)))
{
/* Ensures that top element of the stack is always smallest number of the array */
if(*(a+i)<s.items[s.top])
{
push(&s,*(a+i));
}
else
push(&s,s.items[s.top]);
}
}
/* Print the array */
printarray(a,n);
printf("\n");
/* Print the stack */
printstack(&s);
printf("\n");
/* Print the first smallest element of the array */
printf("The First Smallest element is %d\n",smallest(&s));
/* Print the second smallest element of the array */
printf("The Second Smallest element is %d\n",smallest(&s));
return 0;
}