i can't point out the mistake in algo but i can suggest you a good algo for the same
a[] is the sorted array of size n b[] is the sorted array of size 2n in which n elements are absent. now shift all the elements of b[] to the end leaving the first n positions vacant(sorted order in b[] is still unaffected) now merge these two arrays a[] b[], compare a[0...n] b[n.....2n] and put the smaller element in b[] this will give you the required array . On Fri, Jul 22, 2011 at 7:08 AM, vetri <[email protected]> wrote: > question:given 2 sorted list: a's size=n and b's size=2*n but has only > n elements. > merge them into 1 single list. > answer: > i came up with dis but am gettin index out of bound exception. can u > pls spot d mistake? > import java.util.*; > public class merge { > static int a[],b[],size; > > public static void mergeArray(int a[],int b[],int M){ > int N=2*M; > for(int j=0,k=M;j<M;j++,k++){ > b[k]=b[j]; > b[j]=0; > } > > int i=0,j=M,k=0; > do{ > if(i>=M&&j>=N)break; > if(a[i]<=b[j]){ > b[k]=a[i]; > k++; > System.out.print(" "+a[i]); > if(i<M) > i++; > > } > if(b[j]<a[i]){ > b[k]=b[j]; > k++; > if(j<N) > j++; > } > > }while(true); > > while(i==M-1&& j!=N-1){ > b[k++]=b[j++]; > } > > while(i!=M-1&& j==N-1){ > b[k++]=a[i]; > if(i<M)i++; > } > > > > } > > > > public static void main(String args[]){ > Scanner in=new Scanner(System.in); > System.out.println("enter the array size:"); > size=in.nextInt(); > a=new int[size]; > b=new int[size*2]; > System.out.println("enter the array elements:"); > for(int i=0;i<size;i++){ > a[i]=in.nextInt(); > } > System.out.println("enter the 2nd array elements:"); > for(int i=0;i<size;i++){ > b[i]=in.nextInt(); > } > mergeArray(a,b,size); > > System.out.println("enter the sorted elements:"); > for(int i=0;i<2*size;i++){ > System.out.print(" "+b[i]); > } > > > } > } > > -- > You received this message because you are subscribed to the Google Groups > "Algorithm Geeks" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/algogeeks?hl=en. > > -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.
