固定大小为25的浮点数数组上的合并排序(C编程语言)
我的代码如下:固定大小为25的浮点数数组上的合并排序(C编程语言),c,arrays,floating-point,numbers,mergesort,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) /
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++;
}
}
void mergeSort(浮点a[],int first,int last){
//函数对数组执行合并排序,以获得从头到尾的索引
int mid;
//如果子阵列中有多个元素
如果(第一次<最后一次){
中间=(第一个+最后一个)/2;
//合并排序子数组的左半部分
合并排序(a、第一、中间);
//合并排序子数组的右半部分
合并排序(a,中间+1,最后);
//合并2个子阵列
合并(a、第一、中间、最后);
}
}
无效合并(浮点a[],int first,int mid,int last){
//用于合并排序的子阵列a[第一->中间]和
//a[(中间+1)->last]进入已排序的子数组a[第一->最后]
int-ndx1;
int-ndx2;
int last1;
int last2;
int i;
ndx1=第一;
last1=中间;
ndx2=mid+1;
last2=last;
i=0;
//分配与[first,last]大小相同的临时数组
浮子温度[尺寸];
而((ndx1当您(尝试)从数组中的temp
复制回值时
for(j = 0; (last-first) ;j++){
a[j] = temp[i];
i++;
}
对于first!=last
,您有一个无限循环,导致读取和写入超出数组边界,迟早会导致分段错误或访问冲突。当您(尝试)从temp
复制数组中的值时,您的意思是写入j
for(j = 0; (last-first) ;j++){
a[j] = temp[i];
i++;
}
对于first!=last
,您有一个无限循环,这会导致读写超出数组边界,迟早会导致分段错误或访问冲突。您的意思是为固定大小排序写入j排序网络应该是最佳的。25的边界太大,但您可以将其拆分为两半,然后再进行do非递归合并。祝贺达到15个代表!您现在可以增加投票答案了。:)对于固定大小排序,排序网络应该是最佳的。25的边界太大,但您可以将其拆分为一半,然后执行非递归合并。祝贺达到15个代表!您现在可以增加投票答案了。:)现在可以了。非常感谢。快速提问:我确实想写j,因为(j=0;j)的b/w++j和j++到底有什么区别?我使用了j++,我的程序仍然可以工作?啊,那。在这种情况下,这只是一个自定义或首选项的问题。如果使用该值,会有区别(++j
返回递增的值,j++
返回非递增的值),但作为循环计数器增量,任何好的编译器都会将两者转换为相同的代码。我只是习惯于总是在那里写前缀递增运算符。(注意,我在a[j]=temp[I++]
因为差异很重要,我想要旧的值。)好的。我很感谢你愿意解释所有这些。它现在起作用了。非常感谢。快速问题:我确实想写j,因为(j=0;j b/w++j和j++的区别到底是什么?我使用了j++,我的程序仍然可以运行?啊,那就是。在这种情况下,这只是一个自定义或首选项的问题。如果使用该值,则会有区别(++j
返回递增的值,j++
返回非递增的值),但作为循环计数器增量,任何好的编译器都会将两者转换为相同的代码。我只是习惯于在那里编写前缀增量运算符。(请注意,我在a[j]=temp[I++]
中使用了I++
,因为这里的差异很重要,我想要旧的值。)好的。感谢您愿意解释所有这些。