# Insertion Sort(One's Digit) of List in Python

Write a program to read a list containing 3-digit integers only. Then write an insertion sort function that sorts the list on the basis of one's digit of all elements. That is, if given list is: [387, 410, 285, 106] then the sorted list (as per above condition) should be : [410, 285, 106, 387] One's digits are in sorted order (0, 5, 6, 7)

PYTHON PROGRAMMING

# Function to perform insertion sort based on the one's digit of all elements

def insertion_sort_by_ones_digit(arr):

for i in range(1, len(arr)):

key = arr[i]

j = i - 1

key_ones_digit = key % 10 # Extract the one's digit of the current element

# Compare the one's digit of the current element with the previous ones

while j >= 0 and arr[j] % 10 > key_ones_digit:

arr[j + 1] = arr[j]

j -= 1

arr[j + 1] = key

# Read a list containing 3-digit integers only

input_list = [int(x) for x in input("Enter a list of 3-digit integers separated by spaces: ").split()]

# Perform insertion sort based on the one's digit of all elements

insertion_sort_by_ones_digit(input_list)

# Print the sorted list

print("Sorted list based on one's digit of all elements:")

print(input_list)