// 3• WAP using a function that sort an array of integers using stacks .
#include <stdio.h>
#include <stdlib.h>
struct stack
{
int size;
int top;
int *arr;
};
int isEmpty(struct stack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size - 1)
{
return 1;
}
else
{
return 0;
}
}
void push(struct stack *ptr, int val)
{
if (isFull(ptr))
{
printf("Stack Overflow! Cannot push %d to the stack\n", val);
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
int pop(struct stack *ptr)
{
if (isEmpty(ptr))
{
printf("Stack Underflow! Cannot pop from the stack\n");
return -1;
}
else
{
int val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
int stack_top(struct stack *ptr)
{
return ptr->arr[ptr->top];
}
struct stack *sort(struct stack *ptr, struct stack *t)
{
while (!isEmpty(ptr))
{
int tmp = stack_top(ptr);
pop(ptr);
while (!isEmpty(t) && stack_top(t) > tmp)
{
push(ptr, stack_top(t));
pop(t);
}
push(t, tmp);
}
return t;
}
void display(struct stack *ptr)
{
printf("element : ");
int k = ptr->top;
while (k != -1)
{
printf("%d ", ptr->arr[k]);
k--;
}
}
void printArry(int *arr)
{
for (int i = 0; i < 8; i++)
{
printf("%d ", arr[i]);
}
}
void sort_array_using_stack(struct stack *ptr, struct stack *t, int *arr)
{
for (int i = 0; i < 8; i++)
{
push(ptr, arr[i]);
}
printArry(arr);
printf("\n");
ptr = sort(ptr, t);
for (int i = 0; i < 8; i++)
{
arr[i] = stack_top(ptr);
pop(ptr);
}
printArry(arr);
}
int main()
{
//intialisation
int p;
struct stack *sp = (struct stack *)malloc(sizeof(struct stack));
struct stack *t = (struct stack *)malloc(sizeof(struct stack));
printf("enter the size of stack : ");
scanf("%d", &p);
sp->size = p;
sp->top = -1;
sp->arr = (int *)malloc(sp->size * sizeof(int));
t->size = p;
t->top = -1;
t->arr = (int *)malloc(t->size * sizeof(int));
printf("Stack has been created successfully\n");
int arr[8] = {55, 99, 80, 66, 35, 41, 29, 100};
sort_array_using_stack(sp, t, arr);
return 0;
}