📜  bubbleSort - Javascript (1)

📅  最后修改于: 2023-12-03 14:39:36.103000             🧑  作者: Mango

bubbleSort - Javascript

bubbleSort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm is named for the way smaller or larger elements "bubble" to the top of the list.

The sorting is done in-place, meaning it modifies the original array.

Code Implementation

Here's an implementation of bubbleSort in Javascript:

function bubbleSort(arr) {
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        const temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return arr;
}
How it Works

The bubbleSort function takes an array arr as input and returns the sorted array. The function uses two loops to iterate through the array. The outer loop iterates through each element of the array, while the inner loop iterates through all the elements except the last one.

In each iteration of the inner loop, the algorithm compares adjacent elements of the array. If the first element is greater than the second element, then the two elements are swapped. This causes the greater element to "bubble" to the top of the array.

After the first iteration of the inner loop, the last element of the array will be the greatest element. After the second iteration, the second last element will be the next greatest element. This process continues until the entire array is sorted.

Performance

In the worst case scenario where the array is already sorted in reverse order, bubbleSort has a time complexity of O(n^2), where n is the number of elements in the array. This makes it an inefficient algorithm for sorting large arrays.

However, in the best case scenario where the array is already sorted, bubbleSort has a time complexity of O(n), making it a very efficient algorithm.

Conclusion

bubbleSort is a simple, yet inefficient algorithm for sorting arrays. Although it is not suitable for sorting large arrays, it is still a useful algorithm for educational purposes and simple sorting tasks.