1def insertionSort(alist):
2
3 for i in range(1,len(alist)):
4
5 #element to be compared
6 current = alist[i]
7
8 #comparing the current element with the sorted portion and swapping
9 while i>0 and alist[i-1]>current:
10 alist[i] = alist[i-1]
11 i = i-1
12 alist[i] = current
13
14 #print(alist)
15
16 return alist
17
18print(insertionSort([5,2,1,9,0,4,6]))
1def insertion(s):
2 for i in range(0,len(s)-1):
3 if s[i]>s[i+1]:
4 s[i],s[i+1]=s[i+1],s[i]
5 for j in range(i,0,-1):
6 if s[j]<s[j-1]:
7 s[j],s[j-1]=s[j-1],s[j]
8 print(s)
9
10insertion([5,2,1,9,0,4,6])
1#Insertion sort
2ar = [34, 42, 22, 54, 19, 5]
3
4for i in range(1, len(ar)):
5 while ar[i-1] > ar[i] and i > 0:
6 ar[i-1], ar[i] = ar[i], ar[i-1]
7 i -= 1
8print(ar)
9
1// Por ter uma complexidade alta,
2// não é recomendado para um conjunto de dados muito grande.
3// Complexidade: O(n²) / O(n**2) / O(n^2)
4// @see https://www.youtube.com/watch?v=TZRWRjq2CAg
5// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html
6
7function insertionSort(vetor) {
8 let current;
9 for (let i = 1; i < vetor.length; i += 1) {
10 let j = i - 1;
11 current = vetor[i];
12 while (j >= 0 && current < vetor[j]) {
13 vetor[j + 1] = vetor[j];
14 j--;
15 }
16 vetor[j + 1] = current;
17 }
18 return vetor;
19}
20
21insertionSort([1, 2, 5, 8, 3, 4])