2017-10-07 77 views
1

以下代碼使用mergeSort算法對最多包含1500000個數字的數組進行排序。然而,我不斷收到錯誤的線long temp [] = new long[end - start + 1]; Mergesort Algorithm Errors

我不斷收到的錯誤消息是:'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

由於new long[end - start + 1]返回一個指向的內存塊,你需要一個合適的long *變量來接受它:

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

由於您使用new ...[],你必須有一個相應delete[]聲明在完成使用後釋放內存。不要忘了添加以下內容到merge()的末尾:

delete[] temp;