Skip to content

Instantly share code, notes, and snippets.

@manavm1990
Last active December 8, 2020 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manavm1990/14a2072f3935719ceaee55268b32c158 to your computer and use it in GitHub Desktop.
Save manavm1990/14a2072f3935719ceaee55268b32c158 to your computer and use it in GitHub Desktop.
Bubble Sort Demo
const nums = [52, 69, 15, 64, 62]; // Needs to be: [69, 64, 62, 52, 15]
const nums2 = [52, 69, 15, 64, 62];
function bubbleSort(stuffToSortOut) {
// Could start by assuming 'false' ๐Ÿคท๐Ÿพโ€โ™‚๏ธ
let swapped;
do {
swapped = false;
// Keep ๐Ÿƒ๐Ÿพโ€โ™‚๏ธ this thing across all of the indexes in the stuffToSortOut
for (let i = 0; stuffToSortOut.length > 0; i++) {
/**
* IF the current element and the next element are both 'truthy' AND
* IF the current element is LESS THAN the next element
*/
if (stuffToSortOut[i] && stuffToSortOut[i + 1] && stuffToSortOut[i] < stuffToSortOut[i + 1]) {
// Put the current value 'to the side'
const temp = stuffToSortOut[i];
// Replace the current element with the value from the next element
stuffToSortOut[i] = stuffToSortOut[i + 1];
// Replace the next element with the 'side value' ๐Ÿ‘†๐Ÿพ
stuffToSortOut[i + 1] = temp;
swapped = true;
}
}
} while (
// Are we done yet? If not, go back and do it again!
swapped
);
return stuffToSortOut;
}
let isOutOfOrder = true;
do {
console.log(nums);
// [52, 69, ...]
if (nums[0] < nums[1]) {
const sideValue = nums[0]; // 52
nums[0] = nums[1]; // [69, 69, ...]
nums[1] = sideValue; // [69, 52, ...]
}
// [..., 52, 15, ...]
else if (nums[1] < nums[2]) {
const sideValue = nums[1];
nums[1] = nums[2];
nums[2] = sideValue;
}
// [..., 15, 64, ...]
else if (nums[2] < nums[3]) {
const sideValue = nums[2]; // 15
nums[2] = nums[3]; // [..., 64, 64, ...]
nums[3] = sideValue; // [..., 64, 15, ...]
}
// [..., 15, 62]
else if (nums[3] < nums[4]) {
const sideValue = nums[3]; // 15
nums[3] = nums[4]; // [..., 62, 62]
nums[4] = sideValue; // [..., 62, 15]
} else {
isOutOfOrder = false;
}
} while (isOutOfOrder);
console.log(nums);
console.log("๐Ÿ‘๏ธโ€๐Ÿ—จ๏ธ", bubbleSort(nums2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment