Insertion sort
Learning objective
write an algorithm/pseudo-code for sorting by insert and
bubble
Assessment criteria
Write an algorithm/pseudo-code for insertion sort
Overview of the Insertion Sort
Algorithm
Simple Step-by-Step
Sorting Process
Insertion sort works by iterating The algorithm is intuitive and easy
through the list. It selects an to understand. It follows a step-by-
element and inserts it into the step approach, making it suitable for
correct position within the sorted educational purposes and small-
part of the array. scale sorting tasks.
🠶 [Link]
Task-1. Explain the insertion sort algorithm using example
Task 1. Fill the trace table
j i while if [0] [1] [2] [3] [4]
arr[i]<arr[i-1] i>1
arr = [12, 11, 13, 5, 6] 12 11 13 5 6
for j in range(1,len(arr)): 1 1
2 2
i=j
3 3
while arr[i]<arr[i-1]: 3 2
arr[i], arr[i-1] = arr[i-1], arr[i]3 1
if i>1: 4 4
4 3
i=i-1
4 2
print(arr) 4 1
Answer
j i while if [0] [1] [2] [3] [4]
arr[i]<arr[i-1] i>1
arr = [12, 11, 13, 5, 6] 12 11 13 5 6
for j in range(1,len(arr)): 1 1 true 11 12
2 2 false
i=j
3 3 true true 5 13
while arr[i]<arr[i-1]: 3 2 true true 5 12
arr[i], arr[i-1] = arr[i-1], arr[i] 3 1 true 5 11
if i>1: 4 4 true true 6 13
4 3 true true 6 12
i=i-1
4 2 true true 6 11
print(arr) 4 1
Task-2. Write pseudo-code of insertion sort
arr = [12, 11, 13, 5, 6]
for j in range(1,len(arr)):
i=j
while arr[i]<arr[i-1]:
arr[i], arr[i-1] = arr[i-1], arr[i]
if i>1:
i=i-1
print(arr)
Task-2. Pseudo-code
10
Working in pairs
Criterias for poster:
1. Write pseudocode (bubble sort and insertion sort)
2. Change worksheets with other group and make a tracing table
3. Return worksheet and evaluate trace table
4. Write the program code
Task 3. Write down program to implement Insertion
sort.
1) Fill array 20 random numbers [0, 100]
2) Output array
3) Sort array
4) Output new array
Task 4
• Task 1. Fill a one-dimensional array of 8 elements with random integers ranging from 0 to
10. Sort the array elements in descending order.
• Task 2. Fill a one-dimensional array of 20 elements with random integers ranging from -
10 to 10. Sort the first 10 elements of the array in ascending order, and the second 10 in
descending order.
• Task 3. Fill a one-dimensional array of 10 elements with random integers ranging from -2
to 2. Sort in ascending order. Find the largest element and their number.