In this article we will learn about different kind of sorting in array
Bubble Sort in Array
Bubble Sort is like going through the list many times. Each time, you look at two neighboring numbers. If they're in the wrong order, you swap them. You keep doing this until you've gone through the list and no more swaps are needed.
It's called "bubble" because just like bubbles rising to the top, smaller numbers slowly move to their correct places in the list. But this can take a while, especially if you have lots of numbers. There are faster ways to sort things, though!
Example :
const data=[3,2,4,1];
for(let i=0;i<data.length;i++)
{
for(j=0;j<data.length;j++)
{
if(data[j]>data[j+1])
{
let temp=data[j]
data[j]=data[j+1]
data[j+1]=temp
}
}
}
console.log(data);
// --------------------------DRY RUN------------------------------
// [3,2,4,1]
// 0 outer Loop
// 0,2341
// 1,2341
// 2,2314
// 3,2314
// 1 outer Loop
// 0, 2314
// 1, 2134
// 2, 2134
// 4, 2134
// 2 outer Loop
// 0, 1234
// fully sorted Here (Bottom three iteration not required,
it is the disadvantage of the Bubble sort)
// 1, 1234
// 2, 1234
// 3, 1234
0 comments: