简体   繁体   English

合并排序程序不会对具有5个以上元素的数组进行排序

[英]Merge sort program doesn't sort array with more than 5 elements

I'm trying to implement the code for merge sort. 我正在尝试实现用于合并排序的代码。 I use the following code for merge sort, which you can have a look at here . 我将以下代码用于合并排序,您可以在此处查看 The problem is when I run the program, for example, I asked it to sort the array [1, 2, 3, 4, 6, 5] then print out the sorted array, it return the array [-1560047667 1 2 3 4 5]. 问题是当我运行程序时,例如,我要求它对数组[1、2、3、4、6、5]进行排序,然后打印出排序后的数组,然后返回数组[-1560047667 1 2 3 4 5]。 From what I observed, it will not print the value of the largest element in the array correctly. 从我观察到的结果来看,它不会正确打印数组中最大元素的值。 My code is below: 我的代码如下:

#include<stdio.h>
#include<stdlib.h>

void merge_sort(int A[], int start, int end){
    My code for merge sort 
    goes here
}

int main(){
    int n, i, *A;
    A = (int *)malloc(n);
    scanf("%d", &n);
    for(i=0; i<n; i++) scanf("%d", A+i);
    merge_sort(A, 0, n);
    for(i=0; i<n; i++) printf("%d", *(A+i));
}

Any suggestion on what is the mistake I've made? 关于我犯了什么错误的任何建议? I think the problem is at the input/output process, but not quite sure what exactly it is. 我认为问题出在输入/输出过程中,但不确定其确切含义。

Your code is trying to develop psychic powers. 您的代码正在尝试发展心理能力。 You're using n before it gets assigned a value as you use scanf afterwards to find out what n should be. 在使用n之前,先使用n然后再使用scanf找出n应该是什么。 This will lead to undefined behaviour, such as your code only working if there are less than 5 elements. 这将导致不确定的行为,例如您的代码仅在少于5个元素时才起作用。

int n, i, *A;
A = (int *)malloc(n);
scanf("%d", &n);

You're also not allocating enough memory as that will allocate n bytes where as an int will typically be 4 bytes (or more or less depending on your computer's architecture). 您还没有分配足够的内存,因为这将分配n个字节,而int通常为4个字节(或多或少取决于计算机的体系结构)。 The best way to ensure you allocate the right amount of memory is to multiple n by the sizeof(*A) - that is the size of whatever A is a pointer to. 确保分配正确内存量的最佳方法是将sizeof(*A)乘以n即A所指向的指针的大小。 This ensures if you change A to be a different type, the allocation code will continue to be correct. 这样可以确保如果将A更改为其他类型,分配代码将继续正确。

scanf("%d", &n);
A = malloc(n*sizeof(*A));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM