## Two Swaps

### October 23, 2015

This is the kind of brain-teaser interview question that I really don’t like. The answer is simple: use two comparisons to find the smallest item, and swap it into the first position of the array. Then use a third comparison on the two remaining elements and swap if necessary. The “trick” is that it is normal to think about reducing comparisons rather than reducing swaps, and your mind is “thinking comparisons” instead of “thinking swaps,” at least if your mind works the same way as my mind. Here’s the program:

(define (two-swaps a b c) (define-syntax swap! (syntax-rules () ((swap! x y) (let ((z x)) (set! x y) (set! y z))))) (if (< a b) (if (< a c) (swap! a a) (swap! a c)) (if (< b c) (swap! a b) (swap! a c))) (if (< b c) (swap! b b) (swap! b c)) (list a b c))

Note that `swap!`

must be a macro. We did swaps in the two cases where nothing gets swapped, just to show that the algorithm always performs three comparisons and two swaps regardless of the input. Here are the six possible inputs:

> (two-swaps 1 2 3) (1 2 3) > (two-swaps 1 3 2) (1 2 3) > (two-swaps 2 1 3) (1 2 3) > (two-swaps 2 3 1) (1 2 3) > (two-swaps 3 1 2) (1 2 3) > (two-swaps 3 2 1) (1 2 3)

You can run the program at http://ideone.com/PX18Ar.

If we put the outermost elements in order first, we then just need one more swap to position the centre element:

In Common Lisp; we use symbol-macrolet to define aliases to the places

in the vector:

Here’s a minimal version that only does one true swap, the rest of the sorting is done when copying the data back from local registers to memory:

This reflects what happens with real processors where we need to copy from memory before processing (and copy back afterwards). Here’s an equivalent function written as inline ARM assembler (just been playing with a new Raspberry Pi). Makes nice use of conditional instructions (eg. “movgt” means do a move but only when the last comparison was greater):