Skip to content

Instantly share code, notes, and snippets.

@sghall
Created January 22, 2017 03:53
Show Gist options
  • Save sghall/f2fd434c1e4787ec77350da6a8efd4a6 to your computer and use it in GitHub Desktop.
Save sghall/f2fd434c1e4787ec77350da6a8efd4a6 to your computer and use it in GitHub Desktop.
Bubble Sort in JavaScript
const swap = (arr, index1, index2) => {
[arr[index1], arr[index2]] = [arr[index2], arr[index1]];
};
const bubbleSort = (arr) => {
const len = arr.length;
for (let i = 0; i < len; i++) {
for (let j = 0, k = len - 1 - i; j < k; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
return arr;
};
@sghall
Copy link
Author

sghall commented Jan 22, 2017

Or with no swap function...

const bubbleSort = (arr) => {
  const len = arr.length;

  for (let i = 0; i < len; i++) {
    for (let j = 0, k = len - 1 - i; j < k; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }

  return arr;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment