Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
Repeat the above steps for all elements, except for the last one.
Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
functionsort (elements) { for(vari=0;i<elements.length-1;i++){ for(varj=0;j<elements.length-i-1;j++){ if(elements[j]>elements[j+1]){ varswap=Elements[j]; ELEMENTS[J]=elements[j+1]; Elements[j+1]=swap; } } }}varelements = [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.
Exchange Sort---bubble sort algorithm (JavaScript edition)