Calculate the minimum and maximum no of element comparisons involved in 2 way merge sort, assuming n =2^k , (k > 0) , n is not a power of 2
I am trying to figure out in the case of 2^k the the min comparison for pass one is n/2*1 and pass 2 : n/4 *2 , that’s how we can calculate the nth term
And for max it’s pass 1 : n/2*(1+1-1) and pass 2 : n/4*(2+2-1)
This is questions are from cormen book which is heaven for software engineers
Code :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to merge two sorted halves
int merge(vector<int>& arr, int left, int mid, int right) {
int i = left, j = mid + 1;
int k = 0, comparisons = 0;
vector<int> temp(right - left + 1);
while (i <= mid && j <= right) {
comparisons++;
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (int i = left; i <= right; i++) {
arr[i] = temp[i - left];
}
return comparisons;
}
// Function to perform merge sort and count comparisons
int mergeSort(vector<int>& arr, int left, int right) {
int comparisons = 0;
if (left < right) {
int mid = left + (right - left) / 2;
comparisons += mergeSort(arr, left, mid);
comparisons += mergeSort(arr, mid + 1, right);
comparisons += merge(arr, left, mid, right);
}
return comparisons;
}
int main() {
vector<int> arr = {38, 27, 43, 3, 9, 82, 10};
int n = arr.size();
cout << "Original array: ";
for (int num : arr) cout << num << " ";
cout << endl;
int comparisons = mergeSort(arr, 0, n - 1);
cout << "Sorted array: ";
for (int num : arr) cout << num << " ";
cout << endl;
cout << "Number
of comparisons: " << comparisons << endl;
return 0;
}
Literally the code returns no output no error message, just a segmentation fault
Saumyadeep Chakrabarty is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.