How does JavaScript array implement bubble sort?

Bubble sort is a simple but inefficient sorting algorithm that is often used to sort small datasets. Its principle is to traverse the array multiple times, compare the size of adjacent elements, and exchange their positions as needed, gradually "bubbling" the largest (or smallest) element to one end of the array. This process is repeated until the entire array is sorted.

In JavaScript, we can implement the bubble sort algorithm using:

function bubbleSort(arr) {
  var len = arr.length;
  for (var i = 0; i < len - 1; i++) {
    for (var j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        // 交换位置
        var temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return arr;
}

Let's explain this implementation step by step:

  1. Define a bubbleSortfunction called that takes an array as an argument and returns the sorted array.
  2. Get the length of the array and save it in a variable lenso that it can be used in subsequent loops.
  3. The outer loop for (var i = 0; i < len - 1; i++)is used to control the number of traversals of the bubble sort. Since each round of traversal moves the largest element to the end, a total of len - 1traversals are required.
  4. The inner loop for (var j = 0; j < len - 1 - i; j++)is used to compare adjacent elements and swap their positions. Each round of traversal will move the largest element of the current unsorted part to the end, so the number of inner loops is len - 1 - i.
  5. In the inner loop, conditional statements are used if (arr[j] > arr[j + 1])to determine the size relationship of adjacent elements. If the previous element is greater than the latter element, their positions need to be swapped.
  6. If the position needs to be exchanged, we use a temporary variable tempto save the value of the previous element, then assign the value of the next element to the previous element, and then assign the value in the temporary variable to the next element to complete the exchange of positions.
  7. After the inner loop ends, the largest element of the current unsorted part has been moved to the end.
  8. The outer loop repeats the above steps until all elements are in ascending order.
  9. Finally, the sorted array is returned.

This is how bubble sort is implemented in JavaScript. Despite the inefficiency of the bubble sort algorithm, its implementation is simple and understandable, and it is a viable option for small datasets. However, for large datasets, the performance of bubble sort will drop significantly because its time complexity is O(n^2), where n is the length of the array. This means that as the amount of data increases, the comparison and exchange operations required for sorting will grow quadratically, resulting in inefficiency.

In order to optimize the bubble sort algorithm, some optimization measures can be introduced. For example, a flag can be added to record whether there is an exchange operation in each round of traversal. If no exchange is performed in a certain round, it means that the array is already in order, and the sorting process can be ended in advance.

The improved code looks like this:

function bubbleSort(arr) {
  var len = arr.length;
  var swapped;
  
  for (var i = 0; i < len - 1; i++) {
    swapped = false;

    for (var j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        var temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
        swapped = true;
      }
    }

    if (!swapped) {
      // 没有发生交换,数组已经有序,提前结束
      break;
    }
  }

  return arr;
}

By introducing swappeda flag, we can check in the inner loop whether a swap operation has occurred. If no exchange occurs, it means that the array is already in order, and the outer loop can be exited early, thereby reducing unnecessary comparison and exchange operations.

This improvement can greatly improve the efficiency of bubble sorting, especially for nearly ordered arrays or small data sets, and can significantly reduce the time complexity of sorting.

It should be noted that although bubble sorting is less efficient in practical applications, as a basic sorting algorithm, it is helpful to understand and learn the principles and ideas of sorting algorithms. In actual development, if you need to sort large-scale data, you usually choose more efficient sorting algorithms, such as quick sort, merge sort, etc.

A full set of video tutorials for dark horse programmers from beginners to mastering front-end JavaScript, basic knowledge and practical tutorials on javascript core advanced ES6 syntax, API, advanced js, etc.

Guess you like

Origin blog.csdn.net/Itmastergo/article/details/132618763