Background
I am re-writing a series of algorithms together with a colleague that we are going to later on publish in a packet for the community.
To start, I picked the typical buble sort algorithm.
Objectives
- the function must be pure
- it must be efficient
- it must obey the complexities listed in https://en.wikipedia.org/wiki/Bubble_sort
Please note that by “being pure” it doesn’t mean that it’s inside code cannot have impurity. It merely means that the PUBLIC API of the function must be pure and it must not affect anything outside of its scope.
Code
const isFunction = require("lodash.isfunction"); const cloneDeep = require("lodash.clonedeep"); const defaultCompare = require("./defaultCompare"); const bubble = ( array, fnCompare = defaultCompare ) => { if( !isFunction(fnCompare) ) throw new Error("fnCompare must be a function"); if(!Array.isArray(array)) throw new Error("array must be an Array"); if (array.length === 0) return []; const clonedArray = cloneDeep(array); return recursiveSort( clonedArray, clonedArray.length, fnCompare ); }; const recursiveSort = ( array, unsortedLength, fnCompare ) => { if( unsortedLength === 1 ) return array; let swapped = false; for( let i = 0; i < unsortedLength - 1; i++ ){ if( fnCompare( array[i], array[i + 1] ) > 0 ){ const temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swapped = true; } } //Ensure O(n) if array is already ordered if(!swapped) return array; return recursiveSort( array, unsortedLength - 1, fnCompare ); }; module.exports = bubble;
What do I want?
I am looking for any flaws in the code that could compromise objectives 1 and 3.
If you have an idea on how to improve object 2 (efficiency) I am all ears as well!