Created
July 17, 2017 19:16
-
-
Save tannerwelsh/acaba062da7ed134d3cebe4ae6927c83 to your computer and use it in GitHub Desktop.
Example sort implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A very basic sorting function (not at all optimized) | |
Might be useful if you're trying to understand how Array#sort() works | |
The way this sorting "algorithm" works is as follows: | |
1. start with an unsorted array of items and a comparison function | |
2. iterate through each item in the unsorted array | |
3. if there are no items in the sorted array | |
add this item to the sorted array | |
4. otherwise, start iterating through each item in the sorted array | |
5. call the comparison function with the current unsorted item and the current sorted item | |
6. if the unsorted item is greater than the sorted item | |
go to the next sorted item | |
7. if the unsorted item is less than or equal to the sorted item | |
insert it before the sorted item and break the loop | |
8. if we are at the last index in the sorted array | |
add the unsorted item to the end of the sorted array | |
9. return the sorted array | |
*/ | |
function sort(unsortedArray, compareFunction) { | |
const sortedArray = [] | |
for (var unsortedIndex = 0; unsortedIndex < unsortedArray.length; unsortedIndex++) { | |
const unsortedItem = unsortedArray[unsortedIndex] | |
if (sortedArray.length === 0) { | |
sortedArray.push(unsortedItem) | |
continue | |
} | |
for (var sortedIndex = 0; sortedIndex < sortedArray.length; sortedIndex++) { | |
const sortedItem = sortedArray[sortedIndex] | |
const compareResult = compareFunction(unsortedItem, sortedItem) | |
if (compareResult <= 0) { | |
sortedArray.splice(sortedIndex, 0, unsortedItem) | |
break | |
} | |
if (sortedIndex === sortedArray.length - 1) { | |
sortedArray.push(unsortedItem) | |
break | |
} | |
} | |
} | |
return sortedArray | |
} | |
// | |
// Examples | |
// | |
const unsortedNums = [58, 27, 10, 99, 33, 27] | |
const numSorter = (a, b) => { | |
return a - b | |
} | |
console.log(sort(unsortedNums, numSorter)) | |
const unsortedStrings = ['nickel', 'bananas', 'freedom', 'cat', 'bananas', 'hype'] | |
const stringSorter = (a, b) => { | |
if (a < b) return -1 | |
if (a > b) return 1 | |
return 0 | |
} | |
console.log(sort(unsortedStrings, stringSorter)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment