Docsity

object oriented program exercises, Exercises of Electrical Engineering

Toggle sidebar
bg1
def insertion_sort(arr):
๎˜ ๎˜ for i in range(1, len(arr)):
๎˜ ๎˜ ๎˜ ๎˜ temp = arr[i]
๎˜ ๎˜ ๎˜ ๎˜ j = i - 1
๎˜ ๎˜ ๎˜ ๎˜ while j >= 0 and temp < arr[j]:
๎˜ ๎˜ ๎˜ ๎˜ ๎˜ ๎˜ arr[j + 1] = arr[j]
๎˜ ๎˜ ๎˜ ๎˜ ๎˜ ๎˜ j -= 1
๎˜ ๎˜ ๎˜ ๎˜ arr[j + 1] = temp
๎˜ ๎˜ return arr
n = int(input("Enter the size of the array: "))
arr = []
print("Enter the elements:")
for n in range(n):
๎˜ ๎˜ element = int(input())
๎˜ ๎˜ arr.append(element)
print(f"Original list: {arr}")
sorted_list = insertion_sort(arr)
print(f"Sorted list: {sorted_list}")

Partial preview of the text

Download object oriented program exercises and more Exercises Electrical Engineering in PDF only on Docsity!

def insertion_sort(arr): for i in range( 1 , len(arr)): temp = arr[i] j = i - 1 while j >= 0 and temp < arr[j]: arr[j + 1 ] = arr[j] j -= 1 arr[j + 1 ] = temp return arr n = int(input("Enter the size of the array: ")) arr = [] print("Enter the elements:") for n in range(n): element = int(input()) arr.append(element) print(f"Original list: {arr}") sorted_list = insertion_sort(arr) print(f"Sorted list: {sorted_list}")