合并具有大数组大小的排序分段错误

时间:2013-12-04 02:57:08

标签: c++ mergesort

我有一个合并排序程序,可以很好地处理小数组大小,但是当我尝试对大小为1000的数组进行排序时,我会遇到分段错误。在尝试调试程序之后,看起来seg错误发生在代码块while(i < last1)周围的某处,但是我无法弄清楚出了什么问题。

void mergeSort(long array[], long last1, long last2){
  //Elements in first, second, and merged arrays, respectively                                                                       
  long i = 0;
  long j = last1;
  long k = 0;

  long* temp = new long[last2];

  //Copy the smaller of the two values i and j into the new temp array                                                               
  while(i < last1 && j < last2){
    if(array[i] < array[j]){
      temp[k] = array[i];
      ++i;
      ++k;
    }
    else{
      temp[k] = array[j];
      ++j;
      ++k;
    }
  }

  //Copy the remaining largest elements of the two arrays to temp[]                                                                  
  while(i < last1){
    temp[k] = array[i];
    ++i;
    ++k;
  }
  while(j < last2){
    temp[k] = array[j];
    ++j;
    ++k;
  }

  //Copy the merged elements of the temp array back into the original array                                                          
  for(long m=0; m<last2; ++m){
    array[m] = temp[m];
  }
}


int main(){

 //create array here called array and fill will values

  for(long i=1; i<n; i=(2*i)){
    for(long j=0; j<(n-1); j=(j+(2*i))){
      long end = ((2*i) < (n-j)) ? (2*i) : (n - j);
        function.mergeSort(&array[j], i, end);
    }
  }
  return 0;
}

0 个答案:

没有答案