bubble sort

// 1.0.0 (2021.11.11)
// 1.0.1 - refactor: use while loop instead of recursive function

import { indexOfMaxElement } from '../../ext/Array.js';

/**
 * bubble sort
 * @param {number[]} arr - array of numbers
 */
export function bubbleSort(arr) {

    let copy = arr.slice();	// copy array
    let firstN = arr.length;    // sort first N elements
	
    // while sorting more than one element
    while (firstN > 1) {
	// find index of max element of the first N elements
	const i = copy.indexOfMaxElement(firstN);
        // last index of the first N elements
        const lastIndex = firstN - 1;
	// if max element not the last, swap them.
	if (i !== lastIndex) 
            [copy[i], copy[lastIndex]] = [copy[lastIndex], copy[i]];
        // sort the first N-1 elements.
        firstN -= 1;
    }
  
    return copy;
}

Last updated