gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:56:12 25 4
gpt4 key购买 nike

我的代码如下:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com