insertin sort python code example

Example: insertion sort

// Por ter uma complexidade alta,
// não é recomendado para um conjunto de dados muito grande.
// Complexidade: O(n²) / O(n**2) / O(n^2)
// @see https://www.youtube.com/watch?v=TZRWRjq2CAg
// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html

function insertionSort(vetor) {
    let current;
    for (let i = 1; i < vetor.length; i += 1) {
        let j = i - 1;
        current = vetor[i];
        while (j >= 0 && current < vetor[j]) {
            vetor[j + 1] = vetor[j];
            j--;
        }
        vetor[j + 1] = current;
    }
    return vetor;
}

insertionSort([1, 2, 5, 8, 3, 4])

Tags:

C Example