简体   繁体   中英

(Merge sort) The code is printing nothing

I recently started learning algorithm with C. I tried to implement merge_sort . But the code is printing nothing and I can't find the problem why this happening. If you take a look at the code and give me the solution it would be very helpful for me. Thanks in advance.

Note: Here I didn't give the main function. Only the merge_sort() and merge() functions

#include <stdio.h>

void merge(int a[], int l[], int r[]);

void merge_sort(int a[], int n) {
    if (n < 2) {
        return;
    } else {
        int i;
        int mid = (n - 1) / 2;
        int l[mid], r[n - mid];
        for (i = 0; i < mid; i++) {
            l[i] = a[i];
        }
        for (i = mid; i < n; i++) {
            r[i - mid] = a[i];
        }
        merge_sort(l, mid);
        merge_sort(r, n - mid);
        merge(a, l, r);
    }
}

void merge(int a[], int l[], int r[]) {
    int i = 0;
    int j = 0;
    int k = 0;
    int nl = sizeof(l) / sizeof(l[0]);
    int nr = sizeof(r) / sizeof(r[0]);
    while (i < nl && j < nr) {
        if (l[i] < r[j]) {
            a[k] = l[i];
            i++;
        } else {
            a[k] = r[j];
            j++;
        }
        k++;
    }
    while(i < nl) {
        a[k] = l[i];
        i++;
        k++;
    }
    while (j < nr) {
        a[k] = r[j];
        j++;
        k++;
    }
}

You cannot compute the size of the arrays passed as parameters with int nl = sizeof(l) / sizeof(l[0]); because sizeof(l) is the size of a pointer to int , not that of the array. sizeof(l) only evaluates to the size of the array when the definition of the array is in scope.

You should pass the sizes explicitly as arguments.

Also change the computation for mid : int mid = n / 2;

Here is a modified version:

#include <stdio.h>

void merge(int a[], int l[], int nl, int r[], int nr);

void merge_sort(int a[], int n) {
    if (n < 2) {
        return;
    } else {
        int i;
        int mid = n / 2;
        int l[mid], r[n - mid];
        for (i = 0; i < mid; i++) {
            l[i] = a[i];
        }
        for (i = mid; i < n; i++) {
            r[i - mid] = a[i];
        }
        merge_sort(l, mid);
        merge_sort(r, n - mid);
        merge(a, l, mid, r, n - mid);
    }
}

void merge(int a[], int l[], int nl, int r[], int nr) {
    int i = 0;
    int j = 0;
    int k = 0;
    while (i < nl && j < nr) {
        if (l[i] <= r[j]) {
            a[k] = l[i];
            i++;
        } else {
            a[k] = r[j];
            j++;
        }
        k++;
    }
    while (i < nl) {
        a[k] = l[i];
        i++;
        k++;
    }
    while (j < nr) {
        a[k] = r[j];
        j++;
        k++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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