DATA STRUCTURES Lab # 5
Implementation for
AND ALGORITHMS elementary sorting
algorithms Insertion Sort
What Is a insertion sort algorithm?
• Insertion Sort is a simple, comparison-based
sorting algorithm.
• It builds the sorted array one item at a time
by comparing each item with the elements
in the sorted portion.
• Commonly used for small or nearly sorted
datasets.
How Insertion Sort Works?
•Start with the second element and compare it with the elements in the sorted part of the array.
•Shift elements greater than the current element one position to the right.
•Insert the current element in its correct position.
•Repeat for each element in the array until the entire array is sorted.
.
Pseudocode of
Insertion Sort:
for i = 1 to n-1 do
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key do
arr[j + 1] = arr[j]
j=j-1
arr[j + 1] = key
#include <iostream>
using namespace std;
// Function to perform insertion sort
void insertion_sort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// Move elements that are greater than the
key to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// Function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, n);
insertion_sort(arr, n);
cout << "Sorted array: ";
printArray(arr, n);
return 0;
}
output
Original array: 12 11 13 5 6
Sorted array: 5 6 11 12 13
Question 1: Sorting with Insertion Sort and Output Analysis
1.Write a C++ function called insertion_sort that sorts an array of integers in
ascending order.
2.Use the function to sort the following array: {34, 7, 23, 32, 5, 62}.
3.Print the array before and after sorting.
4.Track the number of comparisons and shifts made during the sorting process, and print
these values after sorting.
Original array: 34 7 23 32 5 62
Sorted array: 5 7 23 32 34 62
Comparisons: [total comparisons]
Shifts: [total shifts]