Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Merge-sort issue! (http://www.go4expert.com/forums/merge-sort-issue-t25927/)

kadmany 28May2011 20:18

Merge-sort issue!
 
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!


All times are GMT +5.5. The time now is 23:28.