Algorithm to count the number of inversions (out of order elements) in an array. Implemented in JavaScript.