开发平台(Platform): (Ex: Win10, Linux, ...)
win7
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
code::block
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
不清楚XD
问题(Question):
先抱歉程式有点冗长不好看,非资工系,最近开始看资结写C
写merge sort,跑出来结果与预期不同
不确定是逻辑与观念错误,还是code写法的问题
喂入的资料(Input):
int numbers[SIZE]={4,15,16,50,8,43,42,108};
预期的正确结果(Expected Output):
{4,8,15,16,42,43,50,108}
错误结果(Wrong Output):
{4,15,16,50,8,43,42,108} 跟输入一样没变
i,j,k那边改成
int i=0;
int j=0;
int k=0;
又会跑出不同的结果
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
int merge(int L[],int R[],int A[]){
int i=0;
int j=0;
int k=0;
while( i<sizeof(L)/sizeof(L[0]) && j<sizeof(R)/sizeof(R[0])){
if(L[i] <= R[j]){
A[k] = L[i];
i++;
}
else{
A[k] = R[j];
j++;
}
k++;
}
while(i<sizeof(L)/sizeof(L[0])){
A[k]=L[i];
i++;
k++;
}
while(j<sizeof(R)/sizeof(R[0])){
A[k]=R[j];
j++;
k++;
}
}
int merge_sort(int array[],int n){
if (n < 2){
return;
}
int mid = n/2;
int left[mid];
int right[n-mid];
for (int i = 0; i < mid-1; i++){
left[i] = array[i];
}
for (int i = mid; i < n-1; i++){
right[i-mid] = array[i];
}
merge_sort(left,mid);
merge_sort(right,n-mid);
merge(left,right,array);
}
int main(void)
{
int numbers[SIZE]={4,15,16,50,8,43,42,108};
printf("\n");
for (int i = 0; i < SIZE; i++){
printf("%i ",numbers[i]);
}
printf("\n");
merge_sort(numbers,SIZE);
for (int i = 0; i < SIZE; i++){
printf("%i ",numbers[i]);
}
printf("\n");
}
补充说明(Supplement):
无