Answers for "insertion sort in python"

1

insertion sort 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]))
Posted by: Guest on December-29-2019
-4

insertion sort in python

def insertion(s):
    for i in range(0,len(s)-1):
        if s[i]>s[i+1]:
            s[i],s[i+1]=s[i+1],s[i]
            for j in range(i,0,-1):
                if s[j]<s[j-1]:
                    s[j],s[j-1]=s[j-1],s[j]
    print(s)
    
insertion([5,2,1,9,0,4,6])
Posted by: Guest on March-01-2021
36

insertion sort python

#Insertion sort
ar = [34, 42, 22, 54, 19, 5]

for i in range(1, len(ar)):
    while ar[i-1] > ar[i] and i > 0:
        ar[i-1], ar[i] = ar[i], ar[i-1]
        i -= 1
print(ar)
Posted by: Guest on July-19-2021
1

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])
Posted by: Guest on May-29-2020
-5

insertion sort in python

def tri_insert(tab): 
for i in range(1, len(tab)): 
        k = tab[i] 
        j = i-1
        while j >= 0 and k < tab[j] : 
                tab[j + 1] = tab[j] 
                j -= 1
        tab[j + 1] = k


    return tab
Posted by: Guest on March-13-2020

Python Answers by Framework

Browse Popular Code Answers by Language