# Bubble Sort

![](https://3743232000-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHW2IQuh2PFpWJDvBz2FF%2Fuploads%2Fgit-blob-e5bc3ddebeef2e21931dc797f29837de3833c05e%2FScreenshot%202023-01-20%20at%2020.26.25.png?alt=media)

* average, worst: n^2, 1
* best: n, 1

```jsx
function bubbleSort(arr) {

  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    let count = 0;
    
    for (let j = arr.length - 1; j > i; --j) {
      if (arr[j - 1] <= arr[j]) continue;
      swap(arr, j - 1, j);
      count++;
    }
    
    if (count === 0) return arr;
  }

  return arr;
}

function swap(arr, a, b) {
  [arr[b], arr[a]] = [arr[a], arr[b]];
  return arr;
}

// Do not edit the line below.
exports.bubbleSort = bubbleSort;
```
