Merge Sort (out of place)
Fri Oct 25 2024 05:50:03 GMT+0000 (Coordinated Universal Time)
Saved by @Rohan@99
#include <iostream>
using namespace std;
// Function to merge two sorted halves of the array into a single sorted array.
void merge(int arr[], int left, int mid, int right)
{
int n1 = mid - left + 1;
int n2 = right - mid;
//temporary arrays
int leftArr[n1], rightArr[n2];
//copy data to temporary arrays
for (int i = 0; i < n1; i++)
leftArr[i] = arr[left + i];
for (int j = 0; j < n2; j++)
rightArr[j] = arr[mid + 1 + j];
//merge temporary arrays back into arr[left..right]
int i = 0, j = 0, k = left;
while (i < n1 && j < n2)
{
if (leftArr[i] <= rightArr[j])
{
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
k++;
}
//copy the remaining elements of leftArr[], if any
while (i < n1)
{
arr[k] = leftArr[i];
i++;
k++;
}
//copy the remaining elements of rightArr[], if any
while (j < n2)
{
arr[k] = rightArr[j];
j++;
k++;
}
}
// Function to recursively divide the array and merge the sorted halves.
void mergeSort(int arr[], int left, int right)
{
if (left < right)
{
int mid = left + (right - left) / 2;
//sort first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
//merge the sorted halves
merge(arr, left, mid, right);
}
}
// Function to initiate the merge sort process.
void processMergeSort(int arr[], int n)
{
if (n > 1)
{
mergeSort(arr, 0, n - 1);
}
}
void displayArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
cout << "Enter the size of the array: ";
cin >> *n;
*arr = new int[*n];
srand(time(0)); // Seed for random number generation
for (int i = 0; i < *n; i++) {
(*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
}
}
int main() {
int* arr;
int n;
fillDynamicArrayWithRandomValues(&arr, &n);
cout << "Unsorted array: ";
displayArray(arr, n);
processMergeSort(arr, n);
cout << "Sorted array: ";
displayArray(arr, n);
delete[] arr; // Deallocate dynamically allocated memory
return 0;
}



Comments