Searches and sorts Flashcards
1
Q
binarySearch(array, target)
A
function binarySearch(array, target) { if (array.length === 0) return -1;
const midpoint = Math.floor(array.length / 2); if (array[midpoint] > target) { return binarySearch(array.slice(0, midpoint), target); } else if (array[midpoint] < target) { const subResult = binarySearch(array.slice(midpoint + 1), target); return subResult === -1 ? -1 : subResult + midpoint + 1; } else { return midpoint; } }
2
Q
bubblesort
A
const defaultCallback = (num1, num2) => { if (num1 < num2) { return -1; } else if (num1 === num2) { return 0; } else { return 1; } };
Array.prototype.bubbleSort = function (callback) {
if (typeof callback !== “function”) {
callback = defaultCallback;
}
let resultArr = this.slice(); let sorted = false; while (!sorted) { sorted = true; for (let i = 1, n = resultArr.length; i < n; i++) { if (callback(resultArr[i - 1], resultArr[i]) === 1) { sorted = false; let swap = resultArr[i - 1]; resultArr[i - 1] = resultArr[i]; resultArr[i] = swap; } } } return resultArr; };
3
Q
jumblesort(str, alphabet = null)
A
function jumbleSort(str, alphabet = null) { alphabet = alphabet || 'abcdefghijklmnopqrstuvwxyz'.split(''); str = str.split('');
let sorted = false; while (!sorted) { sorted = true; for (let i = 0; i < str.length; i++) { if (i === str.length - 1) break; let current = str[i]; let next = str[i + 1]; if (alphabet.indexOf(current) > alphabet.indexOf(next)) { str[i] = next; str[i + 1] = current; sorted = false; } } }
return str.join(‘’);
}
4
Q
mergeSort
A
Array.prototype.mergeSort = function (func) {
if (this.length <= 1) return this;
if (!func) func = (left, right) => {
return left < right ? -1 : left > right ? 1 : 0;
};
const midpoint = Math.floor(this.length / 2); const sortedLeft = this.slice(0, midpoint).mergeSort(func); const sortedRight = this.slice(midpoint).mergeSort(func); return merge(sortedLeft, sortedRight, func); };
function merge(left, right, comparator) { let merged = [];
while (left.length && right.length) { switch (comparator(left[0], right[0])) { case -1: merged.push(left.shift()); break; case 0: merged.push(left.shift()); break; case 1: merged.push(right.shift()); break; } }
merged = merged.concat(left, right);
return merged;
}
5
Q
quicksort
A
Array.prototype.quickSort = function (func) {
if (this.length < 2) return this;
if (!func) { func = (x, y) => { if (x < y) return - 1; return 1; }; }
const pivot = this[0]; let left = this.slice(1).filter((el) => func(el, pivot) === -1); let right = this.slice(1).filter((el) => func(el, pivot) !== -1); left = left.quickSort(func); right = right.quickSort(func);
return left.concat([pivot]).concat(right);
};