PROGRAM 1
Question: Write a program to sort the elements of an array
using Insertion Sort. (The program should report the
number of comparisons.)
CODE:
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n, int &comparisons) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && (++comparisons && arr[j] > key)) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
int n;
cout << "Enter number of elements: ";
cin >> n;
int arr[100];
cout << "Enter elements:\n";
for (int i = 0; i < n; i++)
cin >> arr[i];
int comparisons = 0;
insertionSort(arr, n, comparisons);
cout << "Sorted array:\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
cout << "Total number of comparisons: " << comparisons << endl;
return 0;
}