Bubble sort with optimization
by Arvind Pal
JavaScript
let arr = [8, 1,2,3,4,5,6,7];
let c=0;
/* function bubbleSort(arr){
for(let i=0; i<arr.length; i++){
for(j=0;j<(arr.length-1)-i; j++){
console.log(arr, arr[j], arr[j+1]);
if(arr[j]>arr[j+1]){
let temp=arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
} */
//Optimised code
function bubbleSort(arr){
let noSwap;
for(let i=0; i<arr.length; i++){
noSwap =true
for(j=0;j<(arr.length-1)-i; j++){
console.log(++c, arr, arr[j], arr[j+1]);
if(arr[j]>arr[j+1]){
let temp=arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
noSwap =false;
}
}
if(noSwap)break;
}
}
bubbleSort(arr)
console.log(arr)