1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Merge-sort issue!

Discussion in 'C' started by kadmany, May 28, 2011.

  1. kadmany

    kadmany New Member

    Joined:
    May 28, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    yo yo sup?
    so I get this Merge-Sort to be implemented in c,look:

    **Please notes this:1-The arrays are not sorted and still I got to merge them.

    2-Running time must be of order O(n*log(n))
    3-The following code works but I get Runtime Error,so mainly I need your help to find out where the Runtime Error occurs!
    4-the two arrays of the same size

    Code:
    Code:
    int merge_sort(int arr1[], int n)
    {
    int len;
    int*temp_array,*base;temp_array=(int*)malloc(sizeof(int)*n);
    if(temp_array==NULL){
        printf("Dynamic Allocation Error in merge_sort");
        return FAILURE;
        }
        for(len=1;len<n;len*=2){
            for(base=arr1;base<arr1+n;base+=2*len){
                  merge(base,len,base+len,len,temp_array);
                  memcpy(base,temp_array,1*len*sizeof(int));
                }
            }
        free(temp_array);
        return SUCCESS;
    }
    void merge(int a[],int na,int b[],int nb,int c[])
    {
     int ia,ib,ic;
     for(ia=ib=ic=0;(ia<na) && (ib<nb);ic++){
        if(a[ia]<b[ib]){
            c[ic]=a[ia];
            ia++;
            }
            else{
                c[ic]=b[ib];
                ib++;
                }
        }
        for(;ia<na;ia++,ic++)c[ic]=a[ia];
        for(;ib<nb;ib++,ic++)c[ic]=b[ib];
    }
    
    as u see i implemented merge too,

    My problem is that this code works for arrays of length of (in the fir 'for' loop)power to 2,


    what u think?


    Thanks!
     
    Last edited by a moderator: May 29, 2011

Share This Page