C&S 2024 Exam - Question 3 (a)

 avatar
itsLu
c_cpp
a year ago
1.3 kB
3
Indexable
#include <iostream>
using namespace std;

void Merge2Arrays (int arr[], int first1, int last1, int first2, int last2)
{
    int *tempArray = new int [(last2 - first1) + 1], tempCounter = 0, counter1 = first1, counter2 = first2;
    while (counter1 <= last1 && counter2 <= last2)
    {
        if (arr[counter1] < arr[counter2])
        {
            tempArray[tempCounter] = arr[counter1];
            tempCounter++;
            counter1++;
        }
        else
        {
            tempArray[tempCounter] = arr[counter2];
            tempCounter++;
            counter2++;
        }
    }
    while (counter1 <= last1)
    {
        tempArray[tempCounter] = arr[counter1];
        tempCounter++;
        counter1++;
    }
    while (counter2 <= last2)
    {
        tempArray[tempCounter] = arr[counter2];
        tempCounter++;
        counter2++;
    }
    for (int k = 0 ; k < ((last2 - first1) + 1) ; k++)
        arr[k + first1] = tempArray[k];
    delete[] tempArray;
}

void Merge_Sort(int arr[], int first, int last)
{
    if (first >= last)
        return;
    int mid = ((first + last) / 2);
    Merge_Sort(arr, first, mid);
    Merge_Sort(arr, mid + 1, last);
    Merge2Arrays(arr, first, mid, mid + 1, last);
}
Editor is loading...
Leave a Comment