I'm from Aguascalientes, Mexico! now based on New York. Most of my experience is related to code websites and applications, using JavaScript stack-based.
In some cases the best solution is the one use less operations to perform any task, some of them takes the memory usage, anyhow at least for this one you have to check the operations you are performing to solve this one.
I found something weird, is a bit complex to mentally process at first glance, anyhow it takes more steps that it should.
First:
(function(a){/*Wrapped code to avoid issues with global scop, for quicker experiment*/letoperations=0;constbubbleSort=arr=>{letswapped;do{swapped=false;/* The length is calculated each iteration and most important, you iterate over the entire array multiple times */for(leti=0;i<arr.length;i++,operations++){if(arr[i]>arr[i+1]){lettmp=arr[i];arr[i]=arr[i+1];arr[i+1]=tmp;swapped=true;}}}while(swapped);console.log('Operations:',operations)// Operations: 884returnarr;};bubbleSort(a)})([1,2,6,9,4,1,2,3,5,67,8,9,2,23,5,67,7,678,2,12,34,546,567,678,890,678,34,3453,123,345,46,57,678,4])
You can create an "optimized solution cutting of some iterations"
(function(a){/*wrapping to avoid global scope*/letoperations=0;constbubbleSort=(arr)=>{/* allocating size one time and cutting some iterations starting a second loop on the n+1 array*/for(leti=0,size=arr.length;i<size;i++){for(lete=i+1;e<size;e++,operations++){if(arr[i]>arr[e])[arr[i],arr[e]]=[arr[e],arr[i]]}}returnarr}bubbleSort(a)console.log('Operations',operations)//Operations 561 /*wrapping to avoid global scope*/})([1,2,6,9,4,1,2,3,5,67,8,9,2,23,5,67,7,678,2,12,34,546,567,678,890,678,34,3453,123,345,46,57,678,4])
This is just an experimental case, but in some cases it can crash the app or being unable to perform a task ;)
In some cases the best solution is the one use less operations to perform any task, some of them takes the memory usage, anyhow at least for this one you have to check the operations you are performing to solve this one.
I found something weird, is a bit complex to mentally process at first glance, anyhow it takes more steps that it should.
First:
You can create an "optimized solution cutting of some iterations"
This is just an experimental case, but in some cases it can crash the app or being unable to perform a task ;)
thanks!