Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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)
Comment

How to perform insertion sort, in Python?

"""
This is an implementation of the insertion sort
algorithm. 
Idea is to grow a sorted subset from one element
and then pull all elements of array into that
sorted subset while keeping that subset sorted.
Let n be the size of the list to sort

Time complexity: O(n^2), 
Space complexity: O(1)
"""
def insertion_sort(arr):
    for idx in range(1, len(arr)):
        scan = idx
        while scan > 0 and arr[scan] < arr[scan-1]:
            swap(arr, scan, scan-1)
            scan -= 1
    return arr

def swap(arr, idx1, idx2):
    arr[idx1], arr[idx2] = arr[idx2], arr[idx1]

arr_to_sort = [1, 10, 3, 2]
print(insertion_sort(arr_to_sort))  # [1, 2, 3, 10]
Comment

Python insertion sort

# Insertion sort

def insertionSort(arr):

	for i in range(1, len(arr)):
		key = arr[i]
		j = i-1
		while j >=0 and key < arr[j] :
				arr[j+1] = arr[j]
				j -= 1
		arr[j+1] = key


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
lst = []
print("Sorted array is : ")
for i in range(len(arr)):
	lst.append(arr[i])	 #appending the elements in sorted order
print(lst)

j = i-1
print(range(len(arr)))
print(i)
print(arr[j])

Comment

insertion sort python

# Python program for implementation of Insertion Sort
  
# Function to do insertion sort
def insertionSort(arr):
  
    # Traverse through 1 to len(arr)
    for i in range(1, len(arr)):
  
        key = arr[i]
  
        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        j = i-1
        while j >= 0 and key < arr[j] :
                arr[j + 1] = arr[j]
                j -= 1
        arr[j + 1] = key
  
  
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
    print ("% d" % arr[i])
  
# This code is contributed by Mohit Kumra
Comment

insertion sort python

"""Insertion sort
	1. Unoptimised (continuous swap method)
      1.1 While loop version*
        1.1.1 One with range() and len()
        --> More readable? 
        --> More representative of insertion sort

        1.1.2 One with enumerate()
		--> More pythonic? 
        --> Negligibly slower by comparing 1 more element per iteration
        
      1.2 For loop version
	
	2. Semi-optimised (writing method with while loop) 
    --> but with pythonic enumerate()

*IF YOU ARE NEW TO INSERTION SORT, I SUGGEST LEARNING THE UNOPTIMISED CODES, 
 ESPECIALLY 1.1, BEFORE LEARNING THE SEMI-OPTIMISED VERSION.
**BUILD A SOLID FOUNDATION FOR YOUR UNDERSTANDING OF SORTS
"""
>>> Unoptimised -------------------------------------------------------------
# Method 1.1.1
def insertion_1(lst): 
    # Check all numbers from 2nd number
    for i in range(1, len(lst)):
        # Not smallest number AND curr < prev
        while i != 0 and lst[i] < lst[i-1]:
            # Swap and update curr index for further comparison
            lst[i-1], lst[i] = lst[i], lst[i-1]
            i -= 1
    return lst # for easy testing

# Method 1.1.2
def insertion_2(lst): 
    # Check all numbers
    for i, _ in enumerate(lst):
        # Not smallest number AND curr < prev
        while i != 0 and lst[i] < lst[i-1]:
            # Swap and update curr index for further comparison
            lst[i-1], lst[i] = lst[i], lst[i-1]
            i -= 1
    return lst # for easy testing

# Method 1.2
def insertion_3(lst): 
    # Check every number
    for i, _ in enumerate(lst):
        # Loop until sorted: Check curr < prev, and swap
        for j in range(i, 0, -1):
            if lst[j] < lst[j-1]:
                lst[j], lst[j-1] = lst[j-1], lst[j]
            else:
                break
    return lst # for easy testing
    
>>> Semi-optimised -------------------------------------------------------   
# Method 2
def insertion_4(nums):
    for i, curr_num in enumerate(nums):
        # write curr to right until find correct index to put curr_num
        while i != 0 and curr_num < nums[i-1]:
            nums[i] = nums[i-1]
            i -= 1
        # Write curr_num into correct spot
        nums[i] = curr_num
    return nums # for easy testing
Comment

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)
Comment

PREVIOUS NEXT
Code Example
Python :: f string round 
Python :: beautifulsoup find by class 
Python :: tkinter load image 
Python :: average value of list elements in python 
Python :: python write array to file 
Python :: how to check opencv version using python 
Python :: python read csv 
Python :: python Key–value database 
Python :: remove non-alphabetic pandas python 
Python :: sum of all nan values pandas 
Python :: matplotlib insert text 
Python :: how to apply labelencoder on multiple columns at once 
Python :: python read url 
Python :: f-string ponto decimal python 
Python :: dataframe select entries that are in a list 
Python :: add all string elements in list python 
Python :: django template capitalize equivalent 
Python :: run JupyterLab 
Python :: read json file python utf8 
Python :: python requests.get timeout 
Python :: reload all extensions discord.py 
Python :: ddos in python 
Python :: python csv write add new line 
Python :: series datetime64 seconds to 0 
Python :: business logic in django 
Python :: find location of library python linux 
Python :: install python 3.6 mac brew 
Python :: mp4 to mp3 in python 
Python :: define a column as index pandas 
Python :: Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module from pip import main 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =