I am using windows 10, Visual Studio Code program. I have written bubble sort function in JS but my array is not included in it.I think I called the function incorrectly. Below I show my code, I will be glad if you can tell me what I did wrong, thanks in advance.
function sorting(arr)
{
for (let i = arr.length - 1; i > 0; i--)
{
for (let i = 0; i < j; i++)
{
if (arr[i] > arr[i + 1])
{
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
}
function aftersort(arr)
{
let = [2, 5, 7, 65, 56, 34];
sorting(arr);
}
console.log(arr);
I tried to give numbers to Array and then used the name of this Array in the function, I got an error that my Array is undefined, then I tried to call the function but nothing has changed
2
Answers
You didn’t call your
aftersort
function. You have a syntax error:let = [2, 5, 7, 65, 56, 34];
.j
is never declaredAnd it still doesn’t work
You had a few issues.
aftersort
function is not neededarr
a valuej
Also, your swap was not working, so I fixed
i
andj
and updated the condition. You need to swap with respect toj
, noti
.You could rewrite this to make is more readable. You could also make the sorted result immutable, by making a copy.