javascript - Constructive bubble sort not working as expected -
i'm trying create simple bubble sort in javascript , cannot understand why code not working, problem seems coming second if statement, not know exact problem browser i'm testing in refuses load page when using code.
var arr = [4, 6, 0, 3, -2, 1]; var arr2 = [arr[0]]; arr.foreach(function(elem){ for(var j=0; j<arr2.length; j++){ if(elem < arr2[j]){ arr2.splice(j, 0, elem); break; } //if number largest on last iteration add end of array if(j == arr2.length-1){ console.log(elem); //problem seems here arr2[arr2.length] = elem; } } }); console.log(arr); console.log(arr2);
you're adding elem
array .splice
if lower arr[j]
never removing old instance of elem
. conesquently, you're adding items array , getting larger. need take out old instance of elem
array array length remains constant iteration iteration.
so, somewhere, should passing 1
second argument of splice
take out of array.
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/splice
Comments
Post a Comment