Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

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
Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #insertion #sort #python
ADD COMMENT
Topic
Name
6+7 =