Golf time
I'm the proud new owner of the most suspicious-looking gift certificate ever:
Despite the fact that it's already expired and the amount has been crossed out multiple times, it's supposedly legit. We'll see if the golf course accepts it..
I won it in the weekly office happy hour competition. This week the challenge was to write an implementation of a function with the signature "void ArraySort(int[] array, int length)" that has O(1) memory usage. This was my entry:
void ArraySort(int _array[], int _length)
{
_asm
{
push _mysort
push 4
mov eax, [_length]
push eax
mov eax, [_array]
push eax
mov eax, [qsort]
call eax
add esp, 16
jmp _done
_mysort:
mov edx, [ebp-8]
mov ecx, [ebp-4]
mov eax, [ecx]
cmp eax, [edx]
jle _le
mov eax, 1
ret
_le:
cmp eax, [edx]
jge _ge
mov eax, -1
ret
_ge:
xor eax, eax
ret
_done:
}
}
I particularly like this implementation because the code for the qsort callback is embedded inside the ArraySort function. I was sad that not everybody else appreciated the sublime beauty of this as much as I did.
March 17th, 2007 - 18:02
The challenge posted by Justin actually specified that the function “return a sorted array” of length N. This is very different than sorting the specified array. Thus, I think this would be an equally acceptable solution.
void ArraySort(int _array[], int _length)
{
memset(_array, 0, _length * sizeof(int));
}
I mean, it’s “sorted”, right?
March 17th, 2007 - 23:49
Yes, indeed that would have worked. In fact Erin’s solution did something similar and returned a ‘sorted array’ that had nothing to do with the input. However the judges looked more for usefulness than strict adherence to what the question specifically asked.
March 18th, 2007 - 08:53
Why assembly? Why not, I suppose you’ll say. 😉
Not knowing x86 assembly, what does “mov eax, [qsort]” do, when “qsort” cannot be found anywhere in your code?
March 18th, 2007 - 14:08
Exactly – why not?
There’s a missing line – “#include stdlib.h”, where qsort() is defined, but WordPress kept eating the stupid triangle brackets so I gave up
March 19th, 2007 - 08:16
That makes sense – I was just highlighting the importance of having precise specs. I’d expect better from a Tester…
Do you even play golf?
March 19th, 2007 - 08:39
I sometimes play golf, but not that much. This will be a good excuse.