python program to implement insertion sort and merge sort using lists

Write a python program to implement insertion sort and merge sort using lists

Program:-

import random

def insertion_sort(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

def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left_half = arr[:mid]
        right_half = arr[mid:]

        merge_sort(left_half)
        merge_sort(right_half)

        i = j = k = 0

        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                arr[k] = left_half[i]
                i += 1
            else:
                arr[k] = right_half[j]
                j += 1
            k += 1

        while i < len(left_half):
            arr[k] = left_half[i]
            i += 1
            k += 1

        while j < len(right_half):
            arr[k] = right_half[j]
            j += 1
            k += 1

# Generate a random list of integers
my_list=[]
for i in range(10):
        my_list.append(random.randint(0, 999))
print("Random list:", my_list)

# Sort using Insertion Sort
insertion_sort(my_list)
print("Sorted array using Insertion Sort:", my_list)

# Sort using Merge Sort
merge_sort(my_list)
print("Sorted array using Merge Sort:", my_list)

Output:-

Unsorted List
[932, 111, 226, 685, 543, 589, 918, 539, 294, 717]
Sorting using Insertion Sort
[111, 226, 294, 539, 543, 589, 685, 717, 918, 932]


Unsorted List
[613, 176, 828, 265, 65, 326, 359, 919, 514, 868]
Sorting using Merge Sort
[65, 176, 265, 326, 359, 514, 613, 828, 868, 919]

Leave a Reply

Your email address will not be published. Required fields are marked *