Last active
December 8, 2020 12:45
-
-
Save manavm1990/14a2072f3935719ceaee55268b32c158 to your computer and use it in GitHub Desktop.
Bubble Sort Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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