BSc (Hons) in Information Technology
Year 1
Data Structures and Algorithms – IT1170
Practical 2 – Insertion Sort
Objectives:
• Understand the working principle of Insertion Sort.
• Implement Insertion Sort in Java
• Solve practice problems related to Insertion Sort.
Insertion Sort
Insertion Sort is a simple and efficient sorting algorithm that works by building a sorted
sequence one element at a time. It starts with the second element, comparing it with the
previous elements, and inserting it into its correct position. This process repeats until the entire
list is sorted.
Key Features:
• Best Case (Already Sorted): O(n)
• Worst Case (Reversed Order): O(n2)
How It Works:
1. Consider the first element as sorted.
2. Pick the next element and compare it with the sorted portion.
3. Shift larger elements to the right to make space.
4. Insert the element in its correct position.
5. Repeat until all elements are sorted.
Use Cases:
• Suitable for small datasets.
• Efficient when the list is nearly sorted.
1
Exercise 1: Basic Implementation of Insertion Sort
1. Write a Java program to implement Insertion Sort to sort an integer array in ascending
order. Save the work as InsertionSort.java. Corresponding pseudocode is given below.
INSERTION-SORT(A)
1 for j = 2 to A.length
2 key = A[j]
3 // Insert A[j] into the sorted sequence A[1..j-1]
4 i = j - 1
5 While i > 0 and A[i] > key
6 A[i+1] = A[i]
7 i = i-1
8 A[i+1] = key
2. Modify the above insertion sort algorithm to sort the array in descending order.
Exercise 2: Counting the Number of Shifts
3. Modify the program to count and display the number of shifts required during the sorting
process.
Exercise 3: Simulation of steps of Insertion Sort
4. Implement a StepSimulation.java program that simulates the step-by-step execution of the
Insertion Sort algorithm. Your program should:
• Take an unsorted list of integers as input.
• Display each step of the sorting process, showing how elements are shifted and
inserted into their correct position.
• At the end, print the final sorted list.
2
Sample output: