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...
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.
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 $)...
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...
I am working through this solution in rstudio and am having trouble fitting this table into...
I am working through this solution in rstudio and am having trouble fitting this table into a linear regression analysis. an answer with corrosponding r code used would be greatly appreciated A study was conducted to determine whether the final grade of a student in an introductory psychology course is linearly related to his or her performance on the verbal ability test administered before college entrance. The verbal scores and final grades for all 1010 students in the class are...
I am having the most trouble with 1d: 1. a. Prove that if f : A...
I am having the most trouble with 1d: 1. a. Prove that if f : A → B, g : B → C, and g ◦f : A → C is a 1-to-1 surjection, then f is 1-to-1 and g is a surjection. Proof. b. Prove that if f : A → B, g : B → C, g ◦ f : A → C is a 1-to-1 surjection, and g is 1-to-1, then f is a surjection. Proof. c....
I am working on these study questions and am having trouble understanding how it all works...
I am working on these study questions and am having trouble understanding how it all works together. Any help would be greatly appreciated!! An all equity firm is expected to generate perpetual EBIT of $50 million per year forever. The corporate tax rate is 0% in a fantasy no tax world. The firm has an unlevered (asset or EV) Beta of 1.0. The risk-free rate is 5% and the market risk premium is 6%. The number of outstanding shares is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT