Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for JS Bubble Sort Algorithm
Manav Misra
Manav Misra

Posted on

     

JS Bubble Sort Algorithm

TLDR

The Problem

// TODO: Sort this from highest to lowest w/o using any 'Array prototype stuff'constnums=[52,69,15,64,62];// Needs to be: [69, 64, 62, 52, 15]
Enter fullscreen modeExit fullscreen mode

You Probably Shouldn't Read/Do This

As this is about an algorithm, this is not actually how you would ever sort anarray. You would use JS' built-insort. So the 'real' solution for 👆🏾 would be:nums.sort((a, b) => b - a)

Stat By Sorting Just The First 2 Elements

Let's just focus on getting[52, 69] to[69, 52]. We will be asimperative as possible, and manually type in everyindex of this small array. As a quick reminder 🎗️, it emans that we will start with the first element -52, which is atindex0 and proceed to the last element atindex4.

The procedure will be:

  1. Confirm that 'index0' and 'index1' are indeed out of order. Is[0]<[1]. We could optionally check that both[0] and[1] are 'truth-y' - but we won't bother for now.
  2. Keep a copy of52 'to the side' bybinding to a 'temp variable.'
  3. Replace52 -'index0'' in the array - with69. We will have 269s now.
  4. Replace the original69 -'index1' - with the 'temp value'52 👆🏾.
// [52, 69, ...]if(nums[0]<nums[1]){constsideValue=nums[0];// 52nums[0]=nums[1];// [69, 69, ...]nums[1]=sideValue;// [69, 52, ...]}
Enter fullscreen modeExit fullscreen mode

Now, Let's Move Across the Whole Array -[52, 69, 15, 64, 62]

// [..., 52, 15, ...] - this is already sorted ✅if(nums[1]<nums[2]){constsideValue=nums[1];nums[1]=nums[2];nums[2]=sideValue;}// [..., 15, 64, ...]if(nums[2]<nums[3]){constsideValue=nums[2];// 15nums[2]=nums[3];// [..., 64, 64, ...]nums[3]=sideValue;// [..., 64, 15, ...]}// [..., 15, 62]if(nums[3]<nums[4]){constsideValue=nums[3];// 15nums[3]=nums[4];// [..., 62, 62]nums[4]=sideValue;// [..., 62, 15]}
Enter fullscreen modeExit fullscreen mode

The results:[52, 69, 64, 62, 15]

So...it's working...but we have to go back to the front of the array and keep checking ituntil there are no elements that are 'out of order.'

Yup...that's a➿. Ado-while ➿. Again, for clarity, we will just keep the 'manualindices.'

do-while 🎼

Ado-while is rarely used, but the concept is that thedo part insures at least 1iteration of the loop. If you've never used b4, kindlyreview the example here b4 proceeding.

This time, we will keep aboolean calledisOutOfOrder. This will stay astrueuntil... it's not 🙄. This will be used in ourwhile to finally exit the ➿.

Along the way, we will useelse to check each 'pair of numbers' one at a time, with a finalelse condition to setisOutOfOrder = false.

letisOutOfOrder=true;do{console.log(nums);// [52, 69, ...]if(nums[0]<nums[1]){constsideValue=nums[0];// 52nums[0]=nums[1];// [69, 69, ...]nums[1]=sideValue;// [69, 52, ...]}// [..., 52, 15, ...]elseif(nums[1]<nums[2]){constsideValue=nums[1];nums[1]=nums[2];nums[2]=sideValue;}// [..., 15, 64, ...]elseif(nums[2]<nums[3]){constsideValue=nums[2];// 15nums[2]=nums[3];// [..., 64, 64, ...]nums[3]=sideValue;// [..., 64, 15, ...]}// [..., 15, 62]elseif(nums[3]<nums[4]){constsideValue=nums[3];// 15nums[3]=nums[4];// [..., 62, 62]nums[4]=sideValue;// [..., 62, 15]}else{isOutOfOrder=false;}}while(isOutOfOrder);console.log(nums);
Enter fullscreen modeExit fullscreen mode

This time, the results are good 🤓!

[ 52, 69, 15, 64, 62][ 69, 52, 15, 64, 62][ 69, 52, 64, 15, 62][ 69, 64, 52, 15, 62][ 69, 64, 52, 62, 15][ 69, 64, 62, 52, 15][ 69, 64, 62, 52, 15]
Enter fullscreen modeExit fullscreen mode

functionbubbleSort

We accomplished our task...sort of. Obviously 🙄, we cannot just manually type in all of theindices. We need to wrap everything up in some sort of loop that proceeds all the way through thearray. So, here is an 'official'bubbleSortfunction.

You will notice a few minor differences, but the logic is largely the same. The most significant difference is that theboolean is checking if 'sorting is complete' rather than if there is anything 'out of order.' In this way, you can hopefully see both approaches.

functionbubbleSort(stuffToSortOut){// Could start by assuming 'false' 🤷🏾‍♂️letswapped;do{swapped=false;// Keep 🏃🏾‍♂️ this thing across all of the indexes in the stuffToSortOutfor(leti=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'consttemp=stuffToSortOut[i];// Replace the current element with the value from the next elementstuffToSortOut[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);returnstuffToSortOut;}
Enter fullscreen modeExit fullscreen mode

And...the results are the same:[69, 64, 62, 52, 15]

The Gist

Consider Building a Practical Application Instead of This 💩

Again, there is no need to actually do all of this bologna. It is just an intellectual exercise to better understand programming...andsome employers might ask you to 'white board' something like this 🤷🏾‍♂️.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a JS Subject Matter Expert (SME) that has spent the past few years spearheading curricula and teaching initiatives at colleges and bootcamps, in person and virtually.
  • Location
    62236
  • Education
    BS - Mech. Eng. - Missouri S&T
  • Joined

More fromManav Misra

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp