Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bubble Sort in Javascript
// Normal
const bubbleSort = function(array) {
let swaps;
do {
swaps = false;
for (let i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
let temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
swaps = true;
}
}
} while (swaps);
return array;
};
// Recursively
const bubbleSort = function (array, pointer = array.length - 1) {
// Base Case
if (pointer === 0) {
return array;
}
for (let i = 0; i < pointer; i++) {
if (array[i] > array[i + 1]) {
let temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
// Recursive call on smaller portion of the array
return bubbleSort(array, pointer - 1);
};
@Jerry-Lau

This comment has been minimized.

Copy link

@Jerry-Lau Jerry-Lau commented Jun 7, 2018

cool

@Jerry-Lau

This comment has been minimized.

Copy link

@Jerry-Lau Jerry-Lau commented Jun 14, 2018

关键在于相互交换数组中元素的位置。

@nick3499

This comment has been minimized.

Copy link

@nick3499 nick3499 commented Aug 17, 2018

The key is to swap the positions of the elements in the array.

const bubblesortOnce = a => {
  for(let i=0; i<a.length; i++)
    if(a[i] > a[i+1])
      [a[i], a[i+1]] = [a[i+1], a[i]] // [ 4, 5 ] --> [ 3, 5 ] --> [ 2, 5 ] --> [ 1, 5 ]
  return a
}
@luckyguy73

This comment has been minimized.

Copy link

@luckyguy73 luckyguy73 commented Apr 25, 2019

@nick3499 your code doesn't work correctly.

bubblesortOnce([99,25,1,109,3,1009,243,345])

gives output:
(8) [25, 1, 99, 3, 109, 243, 345, 1009]

@devreapr

This comment has been minimized.

Copy link

@devreapr devreapr commented Oct 17, 2019

@luckyguy73 try this

function bubbleSort(list){
  let swapped=false;
    list.forEach((item,index)=>{
    if(item>list[index+1]){
      [list[index],list[index+1]] = [list[index+1],list[index]];
      swapped=true;
    }
  });
  if(swapped){
    return bubbleSort(list);
  }
  return list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.