Snippets for a bunch of useful JavaScript algorithms.
naiveSearch() | |
---|---|
Type | Loop in loop |
How it works | Compares a string with another string and returns number of matches found. |
Positive | Simple, good for small data sets. |
Negative | Inefficient for large data sets. |
Efficiency Average | O(n^2) |
bubbleSort() | |
---|---|
Type | Loop in loop |
How it works | Swapping, sorting from smallest to largest. |
Positive | Simple, good for small data sets. |
Negative | Inefficient for large data sets. |
Efficiency Average | O(n^2) |
selectionSort() | |
---|---|
Type | Loop in loop |
How it works | Swapping, sorting from largest to smallest. |
Positive | Simple, good for small data sets. |
Negative | Inefficient for large data sets. |
Efficiency Average | O(n^2) |
insertionSort() | |
---|---|
Type | Loop in loop |
How it works | Sorting into new array. |
Positive | Simple, good for small data sets and nearly sorted data, or when new data is addded continuously. |
Negative | Inefficient for large data sets. |
Efficiency Average | O(n^2) |
mergeSort() | |
---|---|
Type | Recursive with loop |
How it works | Splits arrays until each array has only one item (= is sorted). Then merge and sort each array until there's only one array left. |
Positive | More complex, good for large data sets |
Negative | |
Efficiency Average | O(n log n) |
quickSort() | |
---|---|
Type | Recursive with loop |
How it works | Sets pivot on the mean value, puts smaller numbers left of pivot and larger right of pivot. Then sorts left half and right half of increasingly smaller sizes, until its done. |
Positive | |
Negative | With too large data sets you might run out of call stacks. |
Efficiency Average | O(n log n) |
radixSort() | |
---|---|
Type | Loop in loop |
How it works | Sorts an array of integers by loop-sorting them in buckets by number and then putting them back together. |
Positive | Fast. |
Negative | Only works on integers. |
Efficiency Average | O(n k) |