Jonathan Arevalo
Jonathan Arevalo

Reputation: 11

Mergesort Algorithm Errors

The following code uses the mergeSort algorithms to sort an array of up to 1500000 numbers. However, I keep getting errors for the linelong temp [] = new long[end - start + 1];

The error message I keep getting are: 'initializing': cannot convert from 'long *' to 'long []' and initialization with '{...}' expected for aggregate object.Is there a way fix that particular line?

#ifndef DataGen_h
#define DataGen_h
#include "RandomSupport.h"
#include<limits>
#include<iostream>

void merge(long list[], long start, long end) {

    long middle = (start + end) / 2;


    long temp [] = new long[end - start + 1];
    long temp_index = 0;


    long left = start;
    long right = middle + 1;


    while((left <= middle) && (right <= end)) {

        if (list[left] < list[right]) {              
            temp[temp_index] = list[left];
            temp_index++;
            left++;
        } else {
            temp[temp_index] = list[right];
            temp_index++;
            right++;
        }
    }

    while(left <= middle) {
        temp[temp_index] = list[left];
        temp_index++;
        left++;
    }

    while(right <= end) {
        temp[temp_index] = list[right];
        temp_index++;
        right++;
    }

    for(long i = start; i <= end; i++) {
       list[i] = temp[i - start];
    }
}


void mergeSort(long list[], long start, long end) {
    if(start < end) {

        long middle = (start + end) / 2;

        mergeSort(list, start, middle);
        mergeSort(list, middle + 1, end);

        merge(list, start, end);
    }
}

void efficientRandomSortedList(long temp[], long s){
// Get a new random device
randomizer device = new_randomizer();
// Get a uniform distribution from 1 to 1000
uniform_distribution range = new_distribution(1, 15000000);

for (long i = 0; i < s; i++) {
    // At every cell of the array, insert a randomly selected number
    // from distribution defined above
    temp[i] = sample(range, device);
}

// Now sort the array using insertion_sort
mergeSort(temp,0,s);

Upvotes: 1

Views: 58

Answers (1)

frslm
frslm

Reputation: 2978

Since new long[end - start + 1] returns a pointer to a block of memory, you need an appropriate long * variable to accept it:

long *temp = new long[end - start + 1];

Since you're using new ...[], you must have a corresponding delete[] statement to free the memory when you're done using it. Don't forget to add the following to the end of merge():

delete[] temp;

Upvotes: 1

Related Questions