Question

In: Computer Science

I'm having trouble implementing the merge function on this recursive merge sort. I am not allowed...

I'm having trouble implementing the merge function on this recursive merge sort. I am not allowed to change the parameter list in the functions. This is what I have so far, written in C. So far I've been getting segfaults, and I feel like it's because I'm off by 1, somewhere...

void merge_the_array(int *list, int l1, int h1, int l2, int h2){

// create a temp array for l1-h1

int arr_a[(h1-l1)+1];

// create a temp array for l2-h2, adding 1 for the null

int arr_b[(h2-l2)+1];

// counting variables

int i = 0;

int j = 0;

int k = 0;

// begin merging the arrays

while((i <= h1) && (j <= h2)){

if(arr_a[i] <= arr_b[j]){

arr[k] = arr_a[i];

i++;

}

else{

arr[k] = arr_b[j];

j++;

}

k++;

}

// if a temp array runs out of elements, use the other

while(i <= h1){

arr[k] = arr_a[i];

i++;

k++;

}

while(j <= h2){

arr[k] = arr_b[j];

j++;

k++;

}

}

void merge_sort(int *arr, int low_index, int high_index){

if(low_index != high_index){

// adding 1, because high_index = n-1, low_index = 0, & midpoint = n/2

int mid = ((high_index - low_index)+1) / 2;

int l1 = low_index;

int l2 = mid+1;

int h1 = mid;

int h2 = high_index;

// call merge sort for low to mid

merge_sort(list, l1, h1);

//call merge sort for mid+1 to high

merge_sort(list, l2, h2);

// merge the two halves sorted

merge_the_array(list , l1, h1, l2, h2);

}

}

Solutions

Expert Solution

#include<iostream>
using namespace std;
void merge(int *arr,int start1,int start2,int end){

    int temp[1000000]; // creatting the temporary array for copying the elements
    int s1 = start1; // creatiing s1 variable
    int e1 = start2-1; // creatiing e1 variable
    int s2 = start2; // creatiing s2 variable
    int e2 = end; // creatiing e2 variable
    int k = 0;
    // beginning the merging function
    while(s1<=e1 && s2<=e2){
        if(arr[s1]<arr[s2]){
            temp[k++] = arr[s1++];
        }else{
            temp[k++] = arr[s2++];
        }
    }
    while(s1<=e1){
        temp[k++] = arr[s1++];
    }
    while(s2<=e2){
        temp[k++] = arr[s2++];
    }
    k = 0;
    for(int i=start1;i<=end;i++){
        arr[i] = temp[k++];
    }
    return;
}
void mergeSort(int * arr,int start,int end){
    if(start>=end){ // base condition
        return;
    }

    // start is the start index of the aaray
    // end is the last index of the array
    int mid = (start+end)/2; // mid points to the mid index of the aaray 

    mergeSort(arr,start,mid);// calling the merge sort for the 1st part of the array
     
    mergeSort(arr,mid+1,end);// calling the merge sort for the 2nd part of the array

    merge(arr,start,mid+1,end);// calling the merge function to merge 2 soted array
    return;
}
int main(){
    int arr[100] = {5,7,3,1,8,2};
    mergeSort(arr,0,5); // calling the merge sort function to sort the given array
    for(int i=0;i<6;i++){
        cout<<arr[i]<<endl;
    }
}


Related Solutions

I am having trouble with a C++ code that I'm working on. It is a spell...
I am having trouble with a C++ code that I'm working on. It is a spell checker program. It needs to compare two arrays, a dictionary, and an array with misspelled strings that are compared to the strings in the dictionary. the strings that are in the second array that is not in the Dictionary are assumed to be misspelled. All of the strings in the dictionary are lowercase without any extra characters so the strings that are passed into...
Question I'm having trouble with: Using LISP, write a recursive function that takes a list and...
Question I'm having trouble with: Using LISP, write a recursive function that takes a list and returns the number of times the symbol 'a' occurs in it. Note: do not count a's that might occur in a sublist within the list.
Using dev c++ I'm having trouble with classes. I think the part that I am not...
Using dev c++ I'm having trouble with classes. I think the part that I am not understanding is sending data between files and also using bool data. I've been working on this program for a long time with many errors but now I've thrown in my hat to ask for outside help. Here is the homework that has given me so many issues: The [REDACTED] Phone Store needs a program to compute phone charges for some phones sold in the...
I'm having trouble figuring out the constraints to this problem. I know that I am maximizing...
I'm having trouble figuring out the constraints to this problem. I know that I am maximizing 55x + 45y, however the variables are throwing me off. I only need help on question #1 as it would be a great help to understanding the rest of what the questions are asking. The problem is as follows: NorCal Outfitters manufactures a variety of specialty gear for outdoor enthusiasts. NorCal has decided to begin production on two new models of crampons: the Denali...
write a java merge sort called MERGE-SORT-A(), Using recursive calls and NO INSERTION-SORT() as a sub-procedure.
write a java merge sort called MERGE-SORT-A(), Using recursive calls and NO INSERTION-SORT() as a sub-procedure.
1.)recursive merge sort on a list.(Python) 2.)recursive bubble sort using a list without enumerate() function.(python) Show...
1.)recursive merge sort on a list.(Python) 2.)recursive bubble sort using a list without enumerate() function.(python) Show Base case, and recursive case.
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
I am having trouble understanding what value to use for each function. The question is: "Tom...
I am having trouble understanding what value to use for each function. The question is: "Tom plans to save $88 a month, starting today, for 22 years. Dean plans to save $88 a month for 22 years, starting one month from today. Both Tom and Dean expect to earn an average return o 5.27 percent APR on thier savings and both will make the same number of deposits. At the end of the 22 years, how much more (in $)...
C# Arrays & methods I'm having trouble implementing the GetIntArrayFromUser method in the following problem: Create...
C# Arrays & methods I'm having trouble implementing the GetIntArrayFromUser method in the following problem: Create a method AverageIntArray that takes an array of integers and calculates and returns the average of all values in the array as a double Write a program that uses GetIntArrayFromUser method to get an array of 7 numbers, then calls the AverageIntArray method to get the average then prints all values in the array that are greater than the average.                 Sample run:                                ...
I was able to calculate (a) but I am having trouble with the calculations of (b)....
I was able to calculate (a) but I am having trouble with the calculations of (b). Thanks! The following are New York closing rates for A$/US$ and $/£:                                     A$/$ = 1.5150;               $/£ = $1.2950             (a) Calculate the cross rate for £ in terms of A$ (A$/£).             (b) If £ is trading at A$1.95/£ in London (cross market) on the same day, is there an arbitrage opportunity?  If so, show how arbitrageurs with £ could profit from this opportunity and calculate the arbitrage...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT