// bubble sort in javascript Array.prototype.bubbleSort = function(callback = (a, b) => a > b) { const array = this; for (let i = 0; i < array.length; i++) { let swaps = 0; for (let j = 0; j < array.length - i - 1; j++) { if (callback(array[j], array[j + 1])) { let temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; swaps ++; } } if (swaps === 0) break; } } const array = [21, 1, 2, 6, 10, 12, 10, 21, 5, 9, 0]; // a > b for sorting in ascending order // a < b for descending array.bubbleSort((a, b) => a > b); console.log(array);