Practical 2 - Insertion Sort
Practical 2 - Insertion Sort
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]
4 i = j - 1
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.
2
Sample output: