Q3 A

 avatar
Sameh
c_cpp
a year ago
1.8 kB
6
Indexable
void mergeTwoArrays(int *a , int firstIndexOfFirstArray , int lastIndexOfFirstArray , int firstIndexOfSecondArray , int lastIndexOfSecondArray)
{
    int *tempArray;
    tempArray = new int[((lastIndexOfSecondArray - firstIndexOfFirstArray) + 1)];
    int firstArrayCounter = firstIndexOfFirstArray;
    int secondArrayCounter = firstIndexOfSecondArray;
    int tempArrayCounter = 0;
    while(firstArrayCounter <= lastIndexOfFirstArray && secondArrayCounter <= lastIndexOfSecondArray)
    {
        if (a[firstArrayCounter] < a[secondArrayCounter])
        {
            tempArray[tempArrayCounter] = a[firstArrayCounter];
            tempArrayCounter++;
            firstArrayCounter++;
        }
        else
        {
            tempArray[tempArrayCounter] = a[secondArrayCounter];
            tempArrayCounter++;
            secondArrayCounter++;
        }
    }
    while (firstArrayCounter <= lastIndexOfFirstArray)
    {
        tempArray[tempArrayCounter] = a[firstArrayCounter];
        firstArrayCounter++;
        tempArrayCounter++;
    }
    while (secondArrayCounter <= lastIndexOfSecondArray)
    {
        tempArray[tempArrayCounter] = a[secondArrayCounter];
        secondArrayCounter++;
        tempArrayCounter++;
    }
    for (int i = 0 ; i < ((lastIndexOfSecondArray - firstIndexOfFirstArray) + 1) ; i++)
    {
        a[i + firstIndexOfFirstArray] = tempArray[i];
    }
    delete[] tempArray;
}

void mergeSort(int * a , int firstIndex , int lastIndex)
{
    if (firstIndex >= lastIndex)
        return;
    int midIndex = ((firstIndex + lastIndex) / 2);
    mergeSort(a , firstIndex , midIndex);
    mergeSort(a , midIndex + 1 , lastIndex);
    mergeTwoArrays(a , firstIndex , midIndex , midIndex + 1 , lastIndex);
}
Editor is loading...
Leave a Comment