Below you can find a few examples:
Implementing a simple bubble sort:
I know this is an old post, but since I found it anyone else might as well, so I'll just correct some of the mistakes I noticed.
Both the shift and unshift methods are flawed.
If we'd do the unshift method as shown here, we'd get the following:
say we want to add 1 to the array [2,3,4,5].
As the method suggests, we start with i=1 -> we copy number 2 from position 0 to 1;
next iteration i=2 -> there is number 2 on position 1 from last iteration, so we copy number 2 from position 1 to 2;
by now you already get the picture - in each iteration we copy the number 2 (or whatever you had on position 0 at the beginning) one position higher. After adding number 1 on the 0th position, we get the final array [1,2,2,2,2], which is now what we wanted.
here is a possible fix to that:
this[this.length] = null;/* create a new last element */
this[i] = this[i-1]; /* shift elements upwards */
this = item;
This will start coping items from the higher end and thus keeping the array and making room for the new first element.
As for the shift method - it doesn't return anything, although the description said it would return the first element of an array. Solution:
var t = this;
this[i-1] = this[i] /* shift element downwards */
this.length = this.length-1;
I anyone notices anything wrong with my fixes, go ahead and correct me - after all we're here to do thing the right way :)
Array of Integers
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
@mukeshsoftona How exactly is your post related to the previous messages?
|All times are GMT +5.5. The time now is 14:35.|