Showing posts with label merge. Show all posts
Showing posts with label merge. Show all posts

Saturday, August 9, 2014

Program for merge sort.

Program for merge sort. If you need help, feel free to ask.

#include<stdio.h> void mergesort(int x[20],int n) { int temp[20],i,j,k,l1,l2,size,u1,u2,a; size=1; while(size<n) { l1=0; k=0; while(l1+size<n) { l2=l1+size; u1=l2-1; u2=((l2+size-1<n)?l2+size-1:n-1); for(i=l1,j=l2;i<=u1&&j<=u2;k++) { if(x[i]<=x[j]) { temp[k]=x[i]; i++; } else { temp[k]=x[j]; j++; } } for(;i<=u1;k++) { temp[k]=x[i]; i++; } for(;j<=u2;k++) { temp[k]=x[j]; j++; } l1=u2+1; } for(i=l1;k<n;k++) temp[k++]=x[i]; for(i=0;i<n;i++) x[i]=temp[i]; size=size*2; printf("\n"); for(a=0;a<n;a++) printf("%d ",x[a]); printf("\n"); } } main() { int x[20],n,i; printf("\nEnter the value of the number of elements you wish to enter\n"); scanf("%d",&n); printf("\nEnter values of the elements you wish to sort"); for(i=0;i<n;i++) scanf("%d",&x[i]); printf("\nBefore Sorting this is how it looks\n:"); for(i=0;i<n;i++) printf(" %d",x[i]); mergesort(x,n); }

Program to merge two arrays

Program to merge two arrays. This isnt really an important program. But anyways it might be handy.

#include<stdio.h>
main()
{
 int a[50],b[50],i,j,k;
 printf("Enter the number of elements of the first array:\n");
 scanf("%d",&j);
 printf("Enter the elements of the first array:\n");
 for(i=0;i<j;i++)
 scanf("%d",&*(a+i));
 printf("Enter the number of elements of the second array:\n");
 scanf("%d",&k);
 printf("Enter the elements of the second array:\n");
 for(i=0;i<k;i++)
 scanf("%d",&*(b+i));
 for(i=0;i<k;i++)
 *(a+j+i)=*(b+i);
 j=j+k;
 printf("The merged array is :\n");
 for(i=0;i<j;i++)
 printf("%d\t",*(a+i));
}