Javascript Array swap(firstIndex, secondIndex)
function bubbleSort(arr) { if (arr.length === 0 || arr.length === undefined) { return "No array as arg!" }// ww w. j av a 2s.c om if (arr.length === 1) { return arr; } var swapped = true; while (swapped) { swapped = false; for (let i = 0; i < arr.length; i++) { if (arr[i] > arr[i+1]) { // let temp = arr[i]; // arr[i] = arr[i+1]; // arr[i+1] = temp; arr = arr.swap(arr[i],arr[i+1])// arr.swap(arr[i], arr[i+1]) swapped = true; } } } return arr; } Array.prototype.swap = function(firstIndex, secondIndex) { let temp = firstIndex; this[firstIndex] = this[secondIndex]; this[secondIndex] = this[temp]; } console.log(bubbleSort([8,7,3,2,5,1]));