insertion sort in python
def insertionSort(alist):
for i in range(1,len(alist)):
#element to be compared
current = alist[i]
#comparing the current element with the sorted portion and swapping
while i>0 and alist[i-1]>current:
alist[i] = alist[i-1]
i = i-1
alist[i] = current
#print(alist)
return alist
print(insertionSort([5,2,1,9,0,4,6]))
// 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])