1

My code is as follows:

void mergeSort(float a[], int first, int last) {
     //Function performs a mergeSort on an array for indices first to last
     int mid;
     //if more than 1 element in subarray
     if(first < last){
              mid =(first + last) / 2;
              //mergeSort left half of subarray
              mergeSort(a, first, mid);
              //mergeSort right half of subarray
              mergeSort(a, mid+1, last);
              //merge the 2 subarrays
              merge(a, first, mid, last);
              }
}



void merge(float a[], int first, int mid, int last){
     //Function to merge sorted subarrays a[first -> mid] and 
     //a[(mid+1)-> last] into a sorted subarray a[first->last]

     int ndx1; 
     int ndx2;
     int last1;
     int last2;
     int i;
     ndx1 = first;
     last1 = mid;
     ndx2 = mid + 1;
     last2 = last;
     i = 0;

     //Allocate temporary array with same size as a[first, last]
     float temp[SIZE];

     while((ndx1 <= last1) && (ndx2 <= last2)){
                 if(a[ndx1] < a[ndx2]) {
                            temp[i] = a[ndx1];
                            ndx1 = ndx1 + 1;
                            i++;
                            }
                 else{
                      temp[i] = a[ndx2];
                      ndx2 = ndx2 + 1;
                      i++;
                      }
     }

     while(ndx1 <= last1){
                temp[i] = a[ndx1];
                ndx1 = ndx1 + 1;
                i++;
                }

     while(ndx2 <= last2){
                temp[i] = a[ndx2];
                ndx2 = ndx2+1;
                i++;
                }

     int j;           
     i = 0;
     for(j = 0; (last-first) ;j++){
           a[j] = temp[i];
           i++;
           }

}         

It runs a few times, but then it locks up and says it has stopped working. There are no errors, and I wrote this right from an algorithm sheet. I don't understand why it is locking up. Any help would be appreciated greatly.

4

1 回答 1

1

当您(尝试)从tempint 数组中复制回值时,

 for(j = 0; (last-first) ;j++){
       a[j] = temp[i];
       i++;
       }
  1. 对于first != last,您有一个无限循环,这会导致读取和写入超出数组范围,迟早会导致分段错误或访问冲突。你j <= (last - first)的意思是写成循环条件。但
  2. 您正在复制回数组的错误部分,您总是从 开始a[0],但它应该从 开始a[first],循环应该是

    for(j = first; j <= last; ++j) {
        a[j] = temp[i++];
    }
    
于 2013-04-28T20:46:42.020 回答