IBM Interview Question
I think he meant -sort the numbers while holding them in their variables itself, if that's the case then heres' a probable solution -
For 3 numbers:
#include<stdio.h>
void swap(int *a,int* b){
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
int main(){
int a = 117, b = -5, c =-20;
if(b<a)
swap(&a,&b);
if(c<a)
swap(&c,&a);
if(c<b)
swap(&b,&c);
printf("%d %d %d\n",a,b,c);
return 0;
}
For 4 numbers:
int main(){
int a = 57, b = -41, c = 139, d = 19;
if(b<a)
swap(&a,&b);
if(c<a)
swap(&c,&a);
if(d<a)
swap(&d,&a);
if(c<b)
swap(&c,&b);
if(d<b)
swap(&d,&b);
if(d<c)
swap(&d,&c);
printf("%d %d %d %d\n",a,b,c,d);
return 0;
}
We can do it with a linked list, since it should be possible to sort any n numbers. Insertion can be in such a way that everytime insertion is happening on a sorted list.
This is one of those questions that simply make me go WTF? I wouldn't respond that way in an interview, at least I hope I wouldn't. What I would do is ask the interviewer for clarification
- Developer July 16, 2011At this time my opinion of this question is that it is a crappy question. Now I could just be barking at the moon mad because I just don't get it. I've come across questions like that before that looked 'crappy' that eventually turned out to be quite good, I just didn't understand the context.
Maybe someone else has seen this question before and can at least explain what the context of this question is, or give enough clarification to magically transform it from a crappy question to one that is enlightening.