Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

bubble sort

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

// while continueSorting is true
while (continueSorting) {
  // setting continueSorting false. below check to see if swap,
  // if a swap,continue sorting. If no swaps, 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;
Source by sorting-algorithms.me #
 
PREVIOUS NEXT
Tagged: #bubble #sort
ADD COMMENT
Topic
Name
4+8 =