开发者

Merge Sort in C compiles, but doesn't sort

I made this program to sort an array. It works fine, but it won't sort! Please help me find the error in my logic. Thanks

[UPDATE] It was able to work! I just brought down the i, j, and k as suggested below.Also, from i

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

void mergesort(int[], int, int);
void merge(int [], int low, int mid, int hi); //function prototype

int main()
{
    int arr[]={1,4,78,92,9};
   开发者_JS百科 mergesort(arr,0,5);
    //after mergesort
    for(int i=0; i<5; i++)
    {
        printf("%d, ", arr[i]);
    }
    system("pause");
    return 0;
}

void mergesort(int aptr[], int low, int hi)
{
    int mid =0;
    int rightmax=0;
    int leftmax=0;

    if(low==hi)
    {
        return;
    }
    mid=(low+hi)/2;
    mergesort(aptr, low, mid);
    mergesort(aptr, mid+1, hi);
    merge(aptr, low, mid, hi);
}

void merge(int aptr[], int low, int mid, int hi)
{
    int j, i, k;

    //copy contents of aptr to auxiliary b 
    for(i=low; i<=hi; i++)
    {
        bptr[i]=aptr[i]; 
    }

    // iterate through b as if they were still two arrays, lower and higher
    //copy smaller elements first
    i=low;
    j=mid+1;
    k=low;

    while(i<= mid && j<=hi)
    {
        if(bptr[i]<=bptr[j])//<--put smaller element first
        {
            aptr[k++]=bptr[i++];
        }
        else
        {
            aptr[k++]=bptr[j++];
        }
    } 
    // copy back first half just in case
    while(i<=mid)
    {
        aptr[k++]=bptr[i++];
    }
   }//function


The statement i<= mid && j<=hi is never true when your program executes, hence, the while loop that depends on it is never entered and your code that actually swaps elements is never reached.

After the for loop that precedes it, i is equal to hi, which is always greater than mid. I am guessing you mean to reset i to be equal to low before you enter that while loop.


Here's a suggestion for how to start: put printf() calls into your mergesort() and merge() functions that display the parameters at the start and return of each function call. That might help you figure out what's going on. Asking other people to debug your algorithm isn't going to to help you learn how to program.


As a sundry point I'd like to mention that you've fallen victim to error of possible integer overflow:

mid=(low+hi)/2;

If low and/or hi are big enough, low + hi will overflow, giving you the wrong value for mid. Instead you should do this:

mid = low + (hi - low) / 2;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜