Mergesort算法错误

时间:2017-10-07 18:22:46

标签: c++ mergesort

以下代码使用mergeSort算法对最多150万个数字的数组进行排序。但是,我一直收到第long temp [] = new long[end - start + 1];

的错误

我不断收到的错误消息是:'initializing': cannot convert from 'long *' to 'long []'initialization with '{...}' expected for aggregate object.有没有办法修复该特定行?

#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);

1 个答案:

答案 0 :(得分:1)

由于new long[end - start + 1]返回指向内存块的指针,因此您需要一个适当的long *变量来接受它:

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

由于您正在使用new ...[],因此您必须拥有相应的delete[]语句才能在使用完后释放内存。不要忘记将以下内容添加到merge()

的末尾
delete[] temp;