Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

stack overflow js bubble sort

// Bubble sort is a sorting algorithm that sorts data in an array by looping through the array
// and checking if the current item is greater than the next item.
// It will continue to loop through, swapping the items until they are sorted.
// If no swaps are made during a pass, then the data is sorted and we break the loop.

const bubbleSort = (arr) => {
  // This variable is used to either continue or stop the loop
  let continueSorting = true;

  // while continueSorting true
  while (continueSorting) {
    // Here we are setting continueSorting to false. Because below we check to see if a swap is made,
    // if a swap is made, then we continue sorting. If no swaps were made, then were are done sorting,
    // and stop our while loop.
    continueSorting = false

    // loop through the arr from 0 to next to last
    for(let i = 0; i < arr.length - 1; i++) {
      // check if we need to swap
      if(arr[i] > arr[i + 1]) {
        // swap
        let temp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp;

        // since a swap was made, we want to continue sorting
        continueSorting = true;
      }
    }
  }

  // After all swaps have been made, then we return our sorted array
  return arr;
}

// Tests
console.log(bubbleSort([9, 8, 7, 6, 5, 4, 3, 2, 1] ));
console.log(bubbleSort([1, 2, 3, 4, 5, 6, 7, 8, 9] ));
Comment

PREVIOUS NEXT
Code Example
Javascript :: getinitialprops to a hoc in next js 
Javascript :: linear search algorithm in javascript 
Javascript :: curved lines on google maps usint react 
Javascript :: nextjks using window or document object 
Javascript :: delate char betwen index js 
Javascript :: node mongodb $or 
Javascript :: popos not showing applications 
Javascript :: beanstalk nodejs default port 
Javascript :: difference between var, let, const 
Javascript :: angular remove element from array 
Javascript :: javascript select first element 
Javascript :: client.login(email, password) discord.js 
Javascript :: json ld product schema 
Javascript :: json returning object object 
Javascript :: javascript code to test if screen is idle 
Javascript :: geojson featurecollection 
Javascript :: avoiding 0 at front in javascript 
Javascript :: how to give index in query selector in js 
Javascript :: using filter and pipe in rxjs 
Javascript :: merge in mongodb 
Javascript :: CodePen Home Load iframe on click 
Javascript :: es6 arrow function 
Javascript :: slideshow react npm 
Javascript :: Material-ui snowflake icon 
Javascript :: if operator ternary 
Javascript :: declare array in javascript 
Javascript :: react hooks in codepen 
Javascript :: passport google authentication node js 
Javascript :: vscode jest disable auto run 
Javascript :: python dictionary setdefault in javascript 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =