Detailed description of the Javascript Bubble Sorting Algorithm and the javascript Bubble Sorting Algorithm
Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements until there is no need to compare them.
Copy codeThe Code is as follows:
Function sort (elements ){
For (var I = 0; I <elements. length-1; I ++ ){
For (var j = 0; j <elements. length-i-1; j ++ ){
If (elements [j]> elements [j + 1]) {
Var swap = elements [j];
Elements [j] = elements [j + 1];
Elements [j + 1] = swap;
}
}
}
}
Var elements = [3, 1, 5, 7, 2, 4, 9, 6, 10, 8];
Console. log ('before: '+ elements );
Sort (elements );
Console. log ('after: '+ elements );
Efficiency:
Time Complexity: Best: O (n), worst: O (n ^ 2), average: O (n ^ 2 ).
Space complexity: O (1 ).
Stability: stable.