Interview Question
Software Engineer in Tests// The main logic is to push the lowest element to the bottom of the stack, now this is done by comparing the topmost 2 values, do this recursively !
Sort(stack) {
a = stack.pop()
b = stack.pop()
if( a == null) return;
if (b == null ) return;
if(a < b){
stack.push(a)
stack.push(b)
}
else{
stack.push(b)
sort(stack)
stack.push(a)
sort(stack)
}
}
// trace the algo to better understand
#include<stdio.h>
#include<stddef.h>
#include<stdlib.h>
struct stack
{
int capacity;
int top;
int *array;
}*s=NULL;
void createstack(int size)
{
s=(struct stack*)malloc(sizeof(struct stack));
s->array=(int*)malloc(sizeof(int)*size);
s->top=-1;
s->capacity=size;
printf("\n ** array created succ!!\n");
}
int check(int data)
{
printf("\n inside check");
int temp;
if(s->top==-1)
{
s->array[++s->top]=data;
return ;
}
if(s->array[s->top] <data)
{
s->array[++s->top]=data;
return ;
}
if(s->array[s->top] >data)
{
temp=s->array[s->top--];
printf("temp -->> %d",temp);
check(data);
//push(temp);
s->array[++s->top]=temp;
}
}
int sort()
{
printf("\n inside sort");
int data;
if(s->top==-1)
return ;
else
{
data=s->array[s->top--];
printf("data -->> %d",data);
sort();
check(data);
}
}
void main()
{
int size , no , i;
printf("entre the size of array");
scanf("%d",&size);
createstack(size);
for(i=0;i<size;i++)
{
scanf("%d",&no);
s->array[++s->top]=no;
}
printf("\nvalue of top %d",s->top);
sort();
for(i=0;i<s->capacity;i++)
printf("\n%d",s->array[s->top--]);
}
Please post the questions correctly, i dont think it is possible
- ravikant0909 July 27, 2010