4
I’m solving a question of my course which I need to use a vector ordering algorithm based on the Bubble Sort algorithm.
Making a previous summary, the logic consists of going through all the values of the array, in pairs, comparing each other and checking which one is larger. The largest number will always go to the right, switching with the smallest value, thus always passing the largest number to the extreme right. After passing through all the numbers of the array and sorting the first time, the repetition loop repeats by the number number of the array until all values are sorted.
I wrote this code and it’s functional:
let bubble = [82, 76, 6, 52, 45, 38, 24, 14, 54, 85, 143, 98, 65, 512, 96, 12, 4, 79];
function bubbleSort () {
for (let i = 0; i < bubble.length; i++) {
if (bubble[i] > bubble[i +1]) {
let v1 = bubble[i]
let v2 = bubble[i +1]
bubble[i] = v2
bubble[i +1] = v1
}
}
}
for (let j = 0; j < bubble.length ; j++) {
bubbleSort();
}
console.log(bubble)
Code out:
[
4, 6, 12, 14, 24, 38, 45,
52, 54, 65, 76, 79, 82, 85,
96, 98, 143, 512
]
As I’m still learning, I’d like to know how I could refactor the code so I didn’t need to use a function
to do the second loop repeat. I tried to put it inside for but it ended up returning me undefined
when I print the output on the console. You can give me tips to make the code more readable and simple?
This is exactly what I needed, Luiz! I’m not still thinking of better implementations because I’m going through the path of the stones before arriving at more efficient resources, following the line of my short. It helped me a lot, and the implementation with Boolean killed this question of going through the numbers several times even though they were drawn. Still, I realized that there was no reduction in code execution time (before 0.05~, now 0.05~), there is some explanation for this?
– Diego Augusto F.
Probably the number of elements is so small that it makes little difference. The addition of Boolean avoids some additional iterations, but in almost nothing helps to circumvent the intrinsic inefficiency of this algorithm (
O(N^2)
not very good, in the worst case...). Ah, and as you are new on the site, do not forget to check in the [tour] the best way to say thank you. Welcome. :-)– Luiz Felipe
@Diegoaugustof. You should also see how you are measuring (I use sites like https://jsbench.me) - and I also put an answer with another alternative (but it will not improve that much, Bubble Sort is inefficient by definition)
– hkotsubo