Thread: merge sort

  1. #1
    saurav
    Guest

    merge sort

    i am having a problem with the below problem of merge sort, i am not getting a desired ouput.
    here is the program
    Code:
    /* sorting implementing the technique of merge sort */
    # include<stdio.h>
    # include<conio.h>
    void mergesort(int *,int);
    void main()
    {
    int x[20];int i,n;
    clrscr();
    printf("enter the number of elements of the array ");
    scanf("%d",&n);
    printf("enter the elemnts");
    for(i=0;i<n;i++)
    	scanf("%d",&x[i]);
    mergesort(x,n);
    printf("the sorted elements are\n ");
    for(i=0;i<n;i++)
    {
    	printf("%d",x[i]);
    	printf("\n");
    }
    getch();
    }
    void mergesort(int x[],int n)
    {
    	int aux[20],i,j,k,l1,l2,u1,u2;
    	int size=1;
    	while(size<n)
    	{
    		l1=0;
    		k=0;
    		while(l1+size<n)
    		{
    			l2=l1+size;
    			u2=l2-1;
    			u2=(l2+size-1)? l2+size-1:n-1;
    			for(i=l1,j=l2;i<=u1&&j<=u2;k++)
    				if(x[i]<=x[j])
    					aux[k]=x[i++];
    				else
    					aux[k]=x[j++];
    			for(;i<=u1;k++)
    				aux[k]=x[i++];
    			for(;j<=u2;k++)
    				aux[k]=x[j++];
    			l2=u2+1;
    		 }
    		for(i=l1;k<n;i++)
    			aux[k++]=x[i];
    		for(i=0;i<n;i++)
    			x[i]=aux[i];
    		size*=2;
     }
     }
    every time the program runs,it intakes the values then getting out of the dos shell.


    &#91;code]&#91;/code]tagged by Salem

  2. #2
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    Few people will be able to understand this. Why don't you
    just code it like this

    Code:
    void mergesort(int A[], int p, int r) {
            if (p < r)  {
                  int q = (r - p)/ 2;
                  mergesort(p, q);
                  mergesort(q + 1, r);
                  merge(A, p, q, r);
            }
    }
    
    // merge the sorted A[p..q] with A[q + 1..r] to make
    // a sorted A[p..r]
    void merge(int A[], int p, int q, int r) {
    // code for merge
    
    }

  3. #3
    CS Author and Instructor
    Join Date
    Sep 2002
    Posts
    511
    Again, I agree- adapt his code to work with yours- do not reinvent the wheel.
    Mr. C: Author and Instructor

  4. #4
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    int q = (r - p)/ 2;
    This should be (r + p) / 2;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Merge Sort Help
    By blindman858 in forum C++ Programming
    Replies: 5
    Last Post: 05-14-2005, 09:47 PM
  2. Merge Sort
    By blindman858 in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2005, 11:14 AM
  3. threaded merge sort
    By AusTex in forum Linux Programming
    Replies: 4
    Last Post: 05-04-2005, 04:03 AM
  4. merge sort tutorial from cprogramming.com
    By Micko in forum C Programming
    Replies: 0
    Last Post: 03-15-2005, 09:43 AM
  5. help with merge sort
    By maloy in forum C Programming
    Replies: 4
    Last Post: 03-04-2002, 06:22 PM