c - 对固定大小为 25 的 float 数组进行合并排序(C 编程语言)

标签 c arrays floating-point numbers mergesort

我的代码如下:

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++;
           }

}         

它运行了几次,但随后锁定并表示它已停止工作。没有错误,我是根据算法表写的。我不明白为什么它会被锁定。任何帮助将不胜感激。

最佳答案

当您(尝试)从 temp 复制回值时整型数组,

 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++];
    }
    

关于c - 对固定大小为 25 的 float 数组进行合并排序(C 编程语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16267466/

相关文章:

c++ - IEEE 754 浮点除法的可逆性

c++ - 在 C++ 中生成随机 float 不起作用(Visual Studio 2013)

c - 在 cortex m3(裸机)上使用 arm-none-eabi 禁用默认 malloc

c - Makefile 生成对象但不会运行该文件

javascript - 附加到对象 - javascript

java - 反转数组中元素的顺序

C语言编程问题

c - strcmp 问题

arrays - 是否有从二维数组中提取对角线的下标语法?

language-agnostic - 我应该如何进行浮点比较?