Wednesday, January 8, 2014

Q. Merge Sort

ALGORITHM:-

1.  break  array  into  arr[low..mid]  and  arr[mid+1..high]  until  there  is  1  element  left
2.  merge  these  both  arrays


#include<stdio.h>

void merge(int* arr,int low,int mid,int high)
{
    int b[1000];int i_b=low;
        int i=low,j=mid+1;

while(1)
{
   {
        if(i>mid)
        {
                for(int k=j;k<=high;k++)
                b[i_b++]=arr[k];
             break;
        }
     
        if(j>high)
        {
                for(int k=i;k<=mid;k++)
                b[i_b++]=arr[k];
           break;  
        }
 
   }
     
        if(arr[i]>=arr[j])
        {
        b[i_b++]=arr[j];j++;  
        }
        else
        {
        b[i_b++]=arr[i];i++;
        }    
}
for(int k=low;k<=high;k++)
arr[k]=b[k];
}



void mergeSort(int* arr,int low,int high)
{
if(low==high)
return;
int mid=(low+high) /2;
mergeSort(arr,low,mid);
mergeSort(arr,mid+1,high);
merge(arr,low,mid,high);
}


int main()
{
        int arr[10]={2,3,1,7,4,8,5,6,10,9};
        //int arr[10]={10,9,8,7,6,5,4,3,2,1};
        mergeSort(arr,0,9);
        for(int k=0;k<10;k++)
        printf("%d\t",arr[k]);
        return 0;
}

No comments:

Post a Comment