Bubble Sort in JavaScript
Published
•1 min readHere I am solving a problem with nested loops
// 1. Create nested loop to compare each element with the next element
// 2. Compare each element with next one and if next element is smaller then previous one, swap them
// 3. Repeat step 2 until the end of loop
const kaySort = (arr) => {
for (let i = 0; i < arr.length; i++)
{
for (let j = 0; j < arr.length; j++)
{
if (arr[j+1] < arr[j]) {
let tmpSwap = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmpSwap;
}
}
}
return arr;
}
console.log(kaySort([30,125,15,50]));