Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

bubble sort javascript

function bubbleSort(arr){ 
   const length = arr.length;
   let isSwapped = false;
  
    for(let i = 0; i < length; i++){
        for(let j = 0; j < length; j++){
            if(arr[j] > arr[j+1]){
                //swap
                let temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
              isSwapped = true;
            }
        }
      // IF no two elements were swapped by inner loop, then break
      //i.e. array is already sorted
      if(!isSwapped) break;
    }
    return arr;
}

let a = [99,44,6,2,1,5,63,87,283,4,0];
console.log(bubbleSort(a));
Source by learn.coderslang.com #
 
PREVIOUS NEXT
Tagged: #bubble #sort #javascript
ADD COMMENT
Topic
Name
1+2 =