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 :: if else python 
Python :: python num perfect squares 
Python :: np random seed 
Python :: print in binary python 
Python :: python remove punctuation 
Python :: python env 
Python :: how to convert to string in python 
Python :: python inner join based on two columns 
Python :: use a dictionary to make a column of values 
Python :: pytest multi thread 
Python :: convert string of list to list python 
Python :: find unique char in string python 
Python :: onehotencoder pyspark 
Python :: convert float in datetime python 
Python :: how to check if a input is an integer python 
Python :: shuffle list 
Python :: python Decompress gzip File 
Python :: read file into list python 
Python :: how to use csv in python 
Python :: batchnorm1d pytorch 
Python :: for i in a for j in a loop python 
Python :: python drop all variable that start with the same name 
Python :: select a random element from a list python 
Python :: python average of list 
Python :: find the time of our execution in vscode 
Python :: lowercase all text in a column 
Python :: snakeCase 
Python :: how to iterate through ordereddict in python 
Python :: python 3 replace all whitespace characters 
Python :: replace values in a column by condition python 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =