// perform the bubble sort
function bubleSort(arr,n){
// loop to access each array element
bool swapped;
for(let i=0;i<n-1;i++){
// loop to compare array elements
for(let j=i+1;j<n-i-1;j++){
swapped=false;
// compare two adjacent elements
// change > to < to sort in descending order
if(arr[j] > arr[j+1]){
// swapping occurs if elements
// are not in the intended order
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1]=temp;
swapped = true;
}
// IF no two elements were (Optimized Way To Run Bubble Sort)
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
}
let data = [ -2, 45, 0, 11, -9 ];
let n=5;
// call method using class name
bubleSort(data,n);
console.log("Sorted Array in Ascending Order:");
console.log(data.toString());
To embed this project on your website, copy the following code and paste it into your website's HTML: