“Bubble Sort JavaScript” Kode Jawaban

Bubble Sort JavaScript

bubbleSort(Array) {
    let len = Array.length;
    for (let i = 0; i < len; i++) { //you can also use "for in", so you don't need the variable "len"
        for (let j = 0; j < len; j++) {
            if (Array[j] > Array[j + 1]) {
                let tmp = Array[j];
                Array[j] = Array[j + 1];
                Array[j + 1] = tmp;
            }
        }
    }
    return Array;
};
Anxious Albatross

JavaScript Bubble Sort

const bubbleSort = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i; j++) {
      if (arr[j] > arr[j + 1]) {
        let tmp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = tmp;
      }
    }
  }
  return arr;
}
Mysterious Monkey

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 is 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] ));
Jarett Sisk

Modul Impor JS HTML

<script type="module" src="main.js"></script>
Ugliest Unicorn

Bubble Sort JS

function bubbleSort(nums) {
  let swapped = false;
  let iterations = 0;
  do {
    swapped = false;
    for (let i = 0; i < nums.length - iterations - 1; i++) {
      if (nums[i] > nums[i + 1]) {
        [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]];
        swapped = true;
      }
    }
    iterations++;
  } while (swapped);
  return nums;
}
FADL

Jawaban yang mirip dengan “Bubble Sort JavaScript”

Pertanyaan yang mirip dengan “Bubble Sort JavaScript”

Lebih banyak jawaban terkait untuk “Bubble Sort JavaScript” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya