Click here to Skip to main content
15,878,871 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
public class Mergesort2 
{

	public static void main(String[] args) 
	{
		int array[]={8,3,5,2,7,1,4,6};
		sort(array);
	
	}
	static void sort(int array[])
	{
		int mid=array.length / 2;
		
		if(array.length==1)
			return;
		
		int part1[]=new int[mid];
		int part2[]=new int[array.length-mid];
		
		
		for(int i=0; i<array.length; i++)
		{
			if(i<mid)
			{
				part1[i]=array[i];
				
				
			}
			else
			{
				part2[i-mid]=array[i];
				
			}
		}
		
	   sort(part1);
       sort(part2);
	   merge(part1,part2,array);
	   printarray(array);
	
		
	}
	static void merge(int []part1,int []part2,int []array)
	{
		int index1=0;
		int index2=0;
		
		for(int k=0; k<array.length; k++)
		{
			if(index1==part1.length)
			{
				array[k]=part2[index2];
				index2++;
				
			}
			else if(index2==part2.length)
			{
				array[k]=part1[index1];
				index1++;
				
			}
			else if(part1[index1]<=part2[index2])
			{
				array[k]=part1[index1];
				index1++;
				
			}
			else
			{
				array[k]=part2[index2];
				index2++;
				
			}
		}
	}
	static void printarray(int []array)
	{
		
		for(int i=0; i<array.length; i++)
		{
		System.out.print(array[i]+",");
		}
		System.out.println();
		System.out.println("========================");
	}

}
//OUTPUT
//3,8,
//========================
//2,5,
//========================
//2,3,5,8,
//========================
//1,7,
//========================
//4,6,
//========================
//1,4,6,7,
//========================
//1,2,3,4,5,6,7,8,
//========================


my tracing first tracing is correct it gives me an output of 3,8 but in second i dont know what to do because as you can see in merge(int []part1,int []part2,int []array) method theres no calling of sort()method i don't know how the program back to the sort(part1)method. guys can you help me when tracing after the printarray(array)method is executed
Posted
Comments
Sergey Alexandrovich Kryukov 13-Mar-14 19:03pm    
You need to start such question with strict formulation of what did you want to achieve.
—SA

1 solution

I would make a static class variable ArrayList or Vector of strings.
Then printarray(array) inside both sort and merge but with prefix for example
sort0: array
sort1: array
merge0: array
then in main print out whole list of strings.
You could also put one printarray(array) before sort() in main() to show original array.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900