Compare adjacent elements. If the first one is bigger than the second one, exchange them for the two.
Do the same work for each pair of adjacent elements, starting from the first pair to the last pair at the end. At this point, the last element should be the largest number.
Repeat the above steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements each time until there are no pairs of numbers that need to be compared.
The code copy 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.