JS-152-Objects-Arrays
  • Introduction
  • 04-Objects
    • OOP-Basics
      • Overview
      • Coding the Example
    • Prototypes
      • Object Prototypes
      • Prototypes Continued
    • Inheritance
      • Inheritance
    • Synopsis
      • Synopsis
    • Challenges
    • Solutions
      • Constructor Function
        • Person Constructor
        • Explanation
      • Inheritance Challenge
        • Code
        • Explanation
      • Family Challenge
        • Child
        • Pet
  • 05-Arrays
    • Array Basics
      • Array Overview
      • Creating an Array
      • Individual Elements and Length
      • Iterating Over Arrays
    • Array Methods
      • Methods Overview
      • .join() Method
      • .reverse() Method
      • .split() Method
      • .replace() Method
      • .splice() Method
      • .map() Method
      • .indexOf() Method
      • .filter() Method
      • .every() Method
    • Palindrome Algorithm
    • Array Challenges
    • Solutions
      • First and Last
        • First Element
        • Last Element
      • Most Frequent
      • Largest and Smallest
        • Single Array
        • Multiple Arrays
      • Missing Number
      • "Arrays" in the DOM
      • Sorting
        • Bubble Sort
        • Selection Sort
    • Resources
Powered by GitBook
On this page
  • Completed Code
  • Explanation
  1. 05-Arrays
  2. Solutions
  3. Sorting

Bubble Sort

You could honestly use any sorting method you could find but we'll start with Bubble Sort.

Completed Code

function bubbleSort(arr){
    var len = arr.length;
    for (var i = len-1; i>=0; i--){
        for( j = 1; j<=i; j++){
            if(arr[j-1]>arr[j]){
                var temp = arr[j-1];
                arr[j-1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
console.log(bubbleSort([207, 150, 71, -25, 369, 246, -13, 22, 150]));

We already know the output is [ -25, -13, 22, 71, 150, 150, 207, 246, 369 ] but how did bubbleSort() get there?

Explanation

  1. bubbleSort compares the first two elements.

  2. 207 > 150, they switch places.

  3. The process is repeated with the next element, 207 is compared to 71.

  4. We switch our comparison number when 207 gets to 369. 369 is larger, so it moves on.

  5. The process stops when we reach the last element in our array. The highest value 369 has "bubbled up" to the top.

  6. We move backwards down the array repeating the process, starting with the comparison of 369 and 150.

  7. After the first full cycle, when it reaches the start of the array again, it should look like [ -25, 150, 71, -13, 207, 246, 22, 150, 369]

  8. We repeat the process until the array has been properly sorted.

PreviousSortingNextSelection Sort

Last updated 7 years ago