Javascript Algorithm Array Sort Bubble Sort 3

Description

Javascript Algorithm Array Sort Bubble Sort 3

 P:Bubble sort works by starting at the first element of an array and comparing it to the second element.

If the first element is greater than the second element, it swaps the two.

It then compares the second to the third, and the third to the fourth, and so on.

In this way, the largest values "bubble" to the end of the array.

Once it gets to the end of the array, it starts over and repeats the process until the array is sorted numerically.

Example usage:

bubbleSort([2, 1, 3]); // yields [1, 2, 3]
const bubbleSort = function(array) {
  // Your code here.
  const arrayLength = array.length;
  for (let i = 1; i < arrayLength; i += 1) {
    let changeCount = 0;
    for (let p = 0; p < arrayLength - i; p += 1) {
      if (array[p] > array[p + 1]) {
        const temp = array[p];//  w  w w.j av  a2s. c  om
        array[p] = array[p + 1];
        array[p + 1] = temp;
        changeCount += 1;
      }
    }
    if (!changeCount) {
      return array;
    }
  }
  return array;
};

console.log(bubbleSort([2, 1, 3, 3, 5, 2, 1, 7]));
console.log(bubbleSort([2, 1, 3, 5, 1, 2, 3, 9, 4, 6]));
console.log(bubbleSort([1, 3, 4, 7, 11, 18, 33, 40]));



PreviousNext

Related