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 :: message tags in django 
Python :: position of legend matplotlib 
Python :: pandas groupby histogram 
Python :: remove last element from dictionary python 
Python :: torchviz 
Python :: how to edit variables with functions in python 
Python :: how to slicing dataframe using two conditions 
Python :: python inspect source code 
Python :: python tkinter quit button 
Python :: huggingface default cache dir 
Python :: write file with python 
Python :: how to create a database in python 
Python :: openpyxl add worksheet 
Python :: python numpy arrays equal 
Python :: how to check if mouse is over a rect in pygame 
Python :: python move directory 
Python :: what is wsgi in python 
Python :: python merge two dictionaries 
Python :: python read column data from text file 
Python :: what is my python working directory 
Python :: python get nth letter of alphabet 
Python :: python prime check 
Python :: pyplot bar plot colur each bar custom 
Python :: python filter 
Python :: selenium webdriver 
Python :: python get name of file 
Python :: pandas apply with multiple arguments 
Python :: python candlestick chart 
Python :: python create list with n elements 
Python :: hotkey python 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =