// We will understand how to implement bubble sort here //Creating a function for bubble sort in which //we will pass array as arguments function bubbleSort(array) { for (var i = 0; i < array.length; i++) { // Last i elements are already in place for (var j = 0; j < array.length - i - 1; j++) { // Checking if the item at present iteration // is greater than the next iteration if (array[j] > array[j + 1]) { // If the condition is true then swap them var temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } console.log("Array after Bubble sort " + array); } var array = [220, 10, 5, 300, 2]; console.log("Array before Bubble sort " + array); // Now pass this array to the bblSort() function bubbleSort(array);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter