lotsoftools

Bubble Sort JavaScript

This snippet provides a concise guide on how to implement Bubble Sort in JavaScript. It includes code and a step by step explanation.

function bubbleSort(array) {let len = array.length, swap = false; for(let i = 0; i < len; i++) {for(let j = 0; j < len; j++) { if(array[j] > array[j+1]) {let temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; swap = true;} } if(!swap) break; } return array;}

This function takes an array as its parameter. The outer loop will run 'len' times, where 'len' is the length of the array.

Inside the outer loop, another loop will iterate over the array. If it finds any pair where the left element is greater than the right one, it will swap them.

Then it sets the 'swap' flag to true, indicating a successful swap. If no swap occurs on a full pass through the array, the function breaks out of the loop, because the array is already sorted.