Home » Core Java » Mergesort algorithm in Java – Code Example

About Rohit Joshi

Rohit Joshi
Rohit Joshi works as a Software Engineer in the Consumer Product Sector. He is a Sun Certified Java Programmer. He had worked in projects related to different domains. He is also involved in system analysis and system designing. He mainly works in Core Java and J2EE technologies but also have good experience in front-end technologies like Javascript and Jquery.

Mergesort algorithm in Java – Code Example

In this article, we will discuss about the Mergsort algorithm. The Mergersort algorithm is much more efficient than some of the other sorting algorithms.

The Mergesort works by sorting and merging two arrays into one. The basic concept of the Mergesort algorithm is the merging of two already sorted-arrays into one array. In the next section, will show how merging works in the Mergesort algorithm.

 
 
 
 

1. Merging two sorted arrays

The merging is done by combining two already sorted arrays into one empty array. Let’s say that, for example, we have two sorted arrays A and B of size 5 and 7. These two arrays will merge into an array C of size 12.

The merging starts by comparing the items one by one from both the sorted arrays, inserting the smaller item into the third array C and incrementing the cursor of the array of the smaller item by one. The process continues until the cursor of any one sorted array scans and compares all the items of the array. Please note that the two arrays do not require to be of the same size.

Let’s have an example on merging two sorted arrays.

MergingExample.java

package com.javacodegeeks.sorting.mergesort;

public class MergingExample {

	
	public static void main(String[] args) {
		int []a = {2,15,22,47,51};
		int []b = {14,18,26,45,49,56,78};
		
		// Array C of sum of size of the two sorted array A and B
		int []c = new int[a.length+b.length];
		
		merge(a,b,c);
		System.out.print("Array a: ");
		printArray(a);
		System.out.println();
		System.out.print("Array b: ");
		printArray(b);
		System.out.println();
		System.out.print("Array c: ");
		printArray(c);
	}

	public static void merge(int []a, int []b, int []c){
		int cursorA = 0,cursorB = 0,cursorC = 0;
		int sizeA = a.length;
		int sizeB = b.length;
		
		// Runs until neither array is empty
		while(cursorA < sizeA && cursorB < sizeB){
			// Compare the items of two arrays and copy the smaller item into to third array
			if(a[cursorA] < b[cursorB]){
				c[cursorC++] = a[cursorA++];
			}else{
				c[cursorC++] = b[cursorB++];
			}
		}
		
		// If array B's cursor scanned and compared all the items of the array
		// but array A's is not
		while(cursorA < sizeA){
			c[cursorC++] = a[cursorA++];
		}
		
		// If array A's cursor scanned and compared all the items of the array
		// but array B's is not
		while(cursorB < sizeB){
			c[cursorC++] = b[cursorB++];
		}
	}
	
	public static void printArray(int []array){
		for(int i : array){
			System.out.print(i+" ");
		}
	}
}

  • If we run the above code, we will have the following results:
Array a: 2 15 22 47 51 
Array b: 14 18 26 45 49 56 78 
Array c: 2 14 15 18 22 26 45 47 49 51 56 78 

In the above example, we took two sorted arrays a and b of sizes 5 and 7 and merged them into the third array c. Please note that we created the array c of size equal to the sum of the two sorted arrays.

The merge() method takes three arrays as parameters, the two sorted arrays a and b and an empty array c which stores the sorted items of the both arrays. We initialized three cursors each pointed to their respective array at position 0. The method runs by the three loops. The first loop runs until neither array a or b get scanned completely. The items from both the arrays get compared and the smaller item copied into the array c. Then the cursor of the smaller item’s array and array c increments to one.

The second while loop runs if, the array b is completely scanned out, but there are items left in the array a. It copies all left items of the array a to the array c. The third loop works similarly, only if, the array a completely scanned out but items left in the array b. It copies all left items of the array b to the array c.

Now, we have seen how to merge the two sorted arrays. Let’s see how to sort an array using the Mergesort.

2. Sorting using Mergesort

The sorting is done using the Mergesort by dividing an array into two sub-arrays, sort each of them, and then merge them into one. The sorting in the two divided sub-arrays are done by again dividing them further until you reach a sub-array with only one item in it. An array containing only one item is assumed to be as sorted.

MergesortExample.java

package com.javacodegeeks.sorting.mergesort;

public class MergesortExample {

	private static int []a;
	public static void main(String[] args) {
		a = getArray();
		printArray(a);
		sort();
		System.out.println();
		printArray(a);
	}
	
	public static void sort(){
		int []tempArray = new int[a.length];
		mergeSort(tempArray,0,a.length-1);
	}
	
	public static void mergeSort(int []tempArray,int lowerIndex,int upperIndex){
		if(lowerIndex == upperIndex){
			return;
		}else{
			int mid = (lowerIndex+upperIndex)/2;
			mergeSort(tempArray, lowerIndex, mid);
			mergeSort(tempArray, mid+1, upperIndex);
			merge(tempArray,lowerIndex,mid+1,upperIndex);
		}
	}
	
	public static void merge(int []tempArray,int lowerIndexCursor,int higerIndex,int upperIndex){
		int tempIndex=0;
		int lowerIndex = lowerIndexCursor;
		int midIndex = higerIndex-1;
		int totalItems = upperIndex-lowerIndex+1;
		while(lowerIndex <= midIndex && higerIndex <= upperIndex){
			if(a[lowerIndex] < a[higerIndex]){
				tempArray[tempIndex++] = a[lowerIndex++];
			}else{
				tempArray[tempIndex++] = a[higerIndex++];
			}
		}
		
		while(lowerIndex <= midIndex){
			tempArray[tempIndex++] = a[lowerIndex++];
		}
		
		while(higerIndex <= upperIndex){
			tempArray[tempIndex++] = a[higerIndex++];
		}
		
		for(int i=0;i<totalItems;i++){
			a[lowerIndexCursor+i] = tempArray[i];
		}
	}
	
	public static void printArray(int []array){
		for(int i : array){
			System.out.print(i+" ");
		}
	}
	
	public static int[] getArray(){
		int size=10;
		int []array = new int[size];
		int item = 0;
		for(int i=0;i<size;i++){
			item = (int)(Math.random()*100); 
			array[i] = item;
		}
		return array;
	}

}
  • If we run the above code, we will have the following results:
96 51 20 98 38 73 23 22 47 30 
20 22 23 30 38 47 51 73 96 98 

In the above example, we have sort an array using the Mergesort. The example has an array a which gets sorted using the Mergesort. The sort() method, initializes a temp array and internally calls the mergeSort() method which performs the merge sort on the array a. The temp array is used to store items of the array a temporally.

The mergeSort() method is the recursive method and has three parameters, a tempArray, a lowerIndex and a upperIndex of the array to be sorted i.e of the array a. The other important method used in the above example is the merge() method which is used to merge the two sub-arrays in one array. In the above example, we have not used multiple arrays, we applied limit boundaries to virtually divide an array into multiple sub-arrays.

Let’s have a deeper look into these methods.

mergeSort(int []tempArray,int lowerIndex,int upperIndex): The mergeSort() method is used to merge sort the given array. It passes three parameters, the tempArray is used as temporally array, and the lowerIndex and the upperIndex is used to divide the array virtually into different sub-arrays.

if(lowerIndex == upperIndex): The if statement is the base statement of this recursive method. If the lowerIndex and the upperIndex are equal that means there is only one item in the array (or sub-array) and does not need to be divided any further.

int mid = (lowerIndex+upperIndex)/2: The mid is used to divide the array or the sub-array into half.

mergeSort(tempArray, lowerIndex, mid): Recursive call to the method, but with different parameters from the lowerIndex to the mid index of the array.

mergeSort(tempArray, mid+1, upperIndex): Recursive call to the method, but with different parameters from the mid+1 index to the upperIndex of the array.

merge(tempArray,lowerIndex,mid+1,upperIndex): The merge() method is used to merge the sorted array.

The concept we used in dividing an array is by restricting the lowerIndex and the upperIndex of the array. Hence, consider the array as a sub-array of the size upperIndex-lowerIndex+1. The merge() method is used to combine the items of that virtually divided sub-arrays in a sorted order starts from the smallest item and ends with the largest item.

The four main fields used in this method are the lowerIndex, midIndex, higherIndex and the upperIndex. These fields are the restriction indexes used to set boundaries in between the array and provides virtually separated sub-arrays.

while(lowerIndex <= midIndex && higerIndex <= upperIndex): The loop works until the lowerIndex is smaller than or equal to the midIndex and the higerIndex is smaller than or equal to the upperIndex of the array a. It means neither of the virtual sub-array is scanned completely.

The next lines of code checks, if the item in the array a at the position pointed by the lowerIndex is smaller than the item in the array a pointed by the higerIndex, then it will be copied to the tempArray. Otherwise, the item at the higerIndex would be copied. These comparisons are used to position the items in sorted order. We copied the smaller item first, and then the next larger one and so on until neither of the limit set for this virtual sub-array is reached.

The two sub-arrays might not be of the same size. So, there could be some cases when the limit is reached for the one sub-array, but not for the other sub-array. Then there is no need for comparison and the next two while loops are used to simply copy the items into the tempArray.

Later, when all the items from the two sub-arrays are copied in sorted order into the tempArray, we override them into the main array a. The above process continues with the different sub-arrays until the all items gets compared and places into their proper sorted place which results into the complete sorted array.

3. Sorting in descending order using Mergesort

So far, we have sort an array in ascending order, i.e. from the smallest item to the largest item. But by making a small change in the algorithm, we can sort an array in descending order, i.e. from the largest item to the smallest item.

MergesortDescendingExample.java

package com.javacodegeeks.sorting.mergesort;

public class MergesortDescendingExample {

	private static int []a;
	public static void main(String[] args) {
		a = getArray();
		printArray(a);
		sort();
		System.out.println();
		printArray(a);
	}

	public static void sort(){
		int []tempArray = new int[a.length];
		mergeSort(tempArray,0,a.length-1);
	}

	public static void mergeSort(int []tempArray,int lowerIndex,int upperIndex){
		if(lowerIndex == upperIndex){
			return;
		}else{
			int mid = (lowerIndex+upperIndex)/2;
			mergeSort(tempArray, lowerIndex, mid);
			mergeSort(tempArray, mid+1, upperIndex);
			merge(tempArray,lowerIndex,mid+1,upperIndex);
		}
	}

	public static void merge(int []tempArray,int lowerIndexCursor,int higerIndex,int upperIndex){
		int tempIndex=0;
		int lowerIndex = lowerIndexCursor;
		int midIndex = higerIndex-1;
		int totalItems = upperIndex-lowerIndex+1;
		while(lowerIndex <= midIndex && higerIndex <= upperIndex){
			if(a[lowerIndex] > a[higerIndex]){
				tempArray[tempIndex++] = a[lowerIndex++];
			}else{
				tempArray[tempIndex++] = a[higerIndex++];
			}
		}

		while(lowerIndex <= midIndex){
			tempArray[tempIndex++] = a[lowerIndex++];
		}

		while(higerIndex <= upperIndex){
			tempArray[tempIndex++] = a[higerIndex++];
		}

		for(int i=0;i<totalItems;i++){
			a[lowerIndexCursor+i] = tempArray[i];
		}
	}

	public static void printArray(int []array){
		for(int i : array){
			System.out.print(i+" ");
		}
	}

	public static int[] getArray(){
		int size=10;
		int []array = new int[size];
		int item = 0;
		for(int i=0;i<size;i++){
			item = (int)(Math.random()*100); 
			array[i] = item;
		}
		return array;
	}

}
  • If we run the above code, we will have the following results:
80 9 42 27 92 47 39 40 49 71 
92 80 71 49 47 42 40 39 27 9 

In the above example, we have Mergesort the given array in a descending order. By making a small change in the program, we have sorted the array in descending order, i.e. items get sorted in an order starts from the largest item at the first index of the array and goes on to the smallest item at the last position in the array.

if(a[lowerIndex] > a[higerIndex]): The only change we have made is in the comparison of the two items in the sub-arrays. This time the larger item gets copied into the tempArray instead of the smaller item. By making this change, the largest item comes at the first position of the array, then the next item, smaller than the item at the first position, and so on, until the last position which contains the smallest item in the array.

The rest of the code remains the same.

4. Mergesort Objects

So far, we have sort an array of integers. In this section, we will see how to sort objects of any type using the Mergesort. We will do this, by creating a sorting utility class, which contains static methods that provides different variations to sort a given array of any class. The utility class contains overloading sort(), in order to provide a variety of sorting options to the given array.

SortingUtility.java

package com.javacodegeeks.sorting.utility;

import java.util.Comparator;
/*
 * The utility class which contains static methods.
 * */
public class SortingUtility {


	// order constants which tells at what order the array should be sort
	public static final int ASC_ORDER = 1;
	public static final int DESC_ORDER = 2;

	/* We want this class as a utility class that contains only static methods.
	 * So, avoiding any creation of an object of this class by keeping its
	 * constructor as private and also throwing an AssertionError to avoid 
	 * any accidently creation of an object within the class. 
	 * */
	private SortingUtility(){
		throw new AssertionError();
	}

	public static<T extends Comparable<T>> void sort(T []a){
		mergeSort(a,0, a.length-1, ASC_ORDER);
	}

	public static<T> void sort(T []a, Comparator<? super T>comparator){
		mergeSort(a,0, a.length-1, ASC_ORDER,comparator);
	}

	public static<T extends Comparable<T>> void sort(T []a,int order){
		mergeSort(a,0, a.length-1, order);
	}

	public static<T> void sort(T []a,int order, Comparator<? super T>comparator){
		mergeSort(a,0, a.length-1, order,comparator);
	}

	public static<T extends Comparable<T>> void mergeSort(T []a,int lowerIndex,int upperIndex,int order){
		if(lowerIndex == upperIndex){
			return;
		}else{
			int mid = (lowerIndex+upperIndex)/2;
			mergeSort(a,lowerIndex,mid,order);
			mergeSort(a,mid+1,upperIndex,order);

			if(order == ASC_ORDER){
				mergeAsc(a,lowerIndex,mid+1,upperIndex);
			}else if(order == DESC_ORDER){
				mergeDesc(a,lowerIndex,mid+1,upperIndex);
			}else{
				throw new UnsupportedOperationException("The order you specified is not supported.");
			}
		}
	}

	public static<T> void mergeSort(T []a,int lowerIndex,int upperIndex,int order, Comparator<? super T>comparator){
		if(lowerIndex == upperIndex){
			return;
		}else{
			int mid = (lowerIndex+upperIndex)/2;
			mergeSort(a,lowerIndex,mid,order,comparator);
			mergeSort(a,mid+1, upperIndex,order,comparator);

			if(order == ASC_ORDER){
				mergeAsc(a,lowerIndex,mid+1,upperIndex,comparator);
			}else if(order == DESC_ORDER){
				mergeDesc(a,lowerIndex,mid+1,upperIndex,comparator);
			}else{
				throw new UnsupportedOperationException("The order you specified is not supported.");
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static<T extends Comparable<T>> void mergeAsc(T []a,int lowerIndexCursor,int higerIndex,int upperIndex){
		Object []tempArray = getTempArray(a.length);
		int tempIndex=0;
		int lowerIndex = lowerIndexCursor;
		int midIndex = higerIndex-1;
		int totalItems = upperIndex-lowerIndex+1;
		while(lowerIndex <= midIndex && higerIndex <= upperIndex){
			if(((Comparable<T>)a[lowerIndex]).compareTo(a[higerIndex]) < 0){
				tempArray[tempIndex++] = a[lowerIndex++];
			}else{
				tempArray[tempIndex++] = a[higerIndex++];
			}
		}

		while(lowerIndex <= midIndex){
			tempArray[tempIndex++] = a[lowerIndex++];
		}

		while(higerIndex <= upperIndex){
			tempArray[tempIndex++] = a[higerIndex++];
		}

		for(int i=0;i<totalItems;i++){
			a[lowerIndexCursor+i] = (T) tempArray[i];
		}
	}


	@SuppressWarnings("unchecked")
	public static<T> void mergeAsc(T []a,int lowerIndexCursor,int higerIndex,int upperIndex,Comparator<? super T>comparator){
		Object []tempArray = getTempArray(a.length);
		int tempIndex=0;
		int lowerIndex = lowerIndexCursor;
		int midIndex = higerIndex-1;
		int totalItems = upperIndex-lowerIndex+1;
		while(lowerIndex <= midIndex && higerIndex <= upperIndex){
			if(comparator.compare(a[lowerIndex],a[higerIndex]) < 0){
				tempArray[tempIndex++] = a[lowerIndex++];
			}else{
				tempArray[tempIndex++] = a[higerIndex++];
			}
		}

		while(lowerIndex <= midIndex){
			tempArray[tempIndex++] = a[lowerIndex++];
		}

		while(higerIndex <= upperIndex){
			tempArray[tempIndex++] = a[higerIndex++];
		}

		for(int i=0;i<totalItems;i++){
			a[lowerIndexCursor+i] = (T) tempArray[i];
		}
	}

	@SuppressWarnings("unchecked")
	public static<T extends Comparable<T>> void mergeDesc(T []a,int lowerIndexCursor,int higerIndex,int upperIndex){
		Object []tempArray = getTempArray(a.length);
		int tempIndex=0;
		int lowerIndex = lowerIndexCursor;
		int midIndex = higerIndex-1;
		int totalItems = upperIndex-lowerIndex+1;
		while(lowerIndex <= midIndex && higerIndex <= upperIndex){
			if(((Comparable<T>)a[lowerIndex]).compareTo(a[higerIndex]) > 0){
				tempArray[tempIndex++] = a[lowerIndex++];
			}else{
				tempArray[tempIndex++] = a[higerIndex++];
			}
		}

		while(lowerIndex <= midIndex){
			tempArray[tempIndex++] = a[lowerIndex++];
		}

		while(higerIndex <= upperIndex){
			tempArray[tempIndex++] = a[higerIndex++];
		}

		for(int i=0;i<totalItems;i++){
			a[lowerIndexCursor+i] = (T) tempArray[i];
		}
	}


	@SuppressWarnings("unchecked")
	public static<T> void mergeDesc(T []a,int lowerIndexCursor,int higerIndex,int upperIndex,Comparator<? super T>comparator){
		Object []tempArray = getTempArray(a.length);
		int tempIndex=0;
		int lowerIndex = lowerIndexCursor;
		int midIndex = higerIndex-1;
		int totalItems = upperIndex-lowerIndex+1;
		while(lowerIndex <= midIndex && higerIndex <= upperIndex){
			if(comparator.compare(a[lowerIndex],a[higerIndex]) > 0){
				tempArray[tempIndex++] = a[lowerIndex++];
			}else{
				tempArray[tempIndex++] = a[higerIndex++];
			}
		}

		while(lowerIndex <= midIndex){
			tempArray[tempIndex++] = a[lowerIndex++];
		}

		while(higerIndex <= upperIndex){
			tempArray[tempIndex++] = a[higerIndex++];
		}

		for(int i=0;i<totalItems;i++){
			a[lowerIndexCursor+i] = (T) tempArray[i];
		}
	}

	private static Object[] getTempArray(int length){
		Object []tempArray = new Object[length];
		return tempArray;
	}
}

The above class SortingUtility is a utility class which contains static methods used to sort a given array of a type T. The class contains overloaded sort() methods. These sort() methods internally call the mergeSort() method to sort the given array.

public static final int ASC_ORDER = 1; : The constant field is used as a flag, if set, the sorting would be done in ascending order.

public static final int DESC_ORDER = 2; : The constant field is used as a flag, if set, the sorting would be done in descending order.

public static<T extends Comparable<T>> void sort(T []a):This method is used to sort a given array of a type T. The class T should implement the Comparable interface and provide an implementation of the overridden comparTo() method, otherwise, it will throw a ClassCastException. Internally, it calls the mergeSort() method which sorts the array in ascending order. It also has a tempArray which is an empty array of size equals to the size of the array a, used temporally to store items of the array a.

public static<T> void sort(T []a, Comparator<? super T>comparator): This method is used to sort a given array of a type T and it also takes an instance of a Comparator interface. The Comparator provides rules to compare the object of the type T. Internally, it calls the mergeSort() method which sorts the array in ascending order.

public static<T extends Comparable<T>> void sort(T []a,int order): This method is used to sort a given array of a type T which should implement the Comparable interface. It also contains an order as its parameter which is used to provide the order in which sorting needs to be done. If the provided value to the order doesn’t match with the flags set in the method, it will throw an UnsupportedOperationException.

public static<T> void sort(T []a,int order, Comparator<? super T>comparator): Works same as the previous discussed method. It also takes an instance of a Comparator interface which provides rules to compare the object of the type T.

All these sort() methods, perform the same functionality. There are two modes of Merge Sort methods used in the above class.

mergeSort(): The mergeSort() is the recursive method which is used to divide the given array into different sub-arrays. Both of the Merge sort methods are in two overloaded forms one of which only has an array of type T and a temp array of type T as its parameter. This method uses the Comparable interface which is implemented by the class T to compare the objects of the type T. The other method passes the Comparator object which defines the rule of comparison between the objects of the type T.

mergeAsc(): Used to sort and merge arrays or sub-arrays in ascending order.
mergeDesc():Used to sort and merge arrays or sub-arrays in descending order.

Employee.java

package com.javacodegeeks.entity;

public class Employee implements Comparable<Employee>{

	private String firstName;
	private String lastName;
	private int emplyeeCode;
	
	public Employee(String fistName,String lastName,int emplyeeCode){
		this.firstName = fistName;
		this.lastName = lastName;
		this.emplyeeCode = emplyeeCode;
	}
	
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getEmplyeeCode() {
		return emplyeeCode;
	}

	public void setEmplyeeCode(int emplyeeCode) {
		this.emplyeeCode = emplyeeCode;
	}

	public String toString(){
		return "Employee Code: "+getEmplyeeCode()+", Name:"+getFirstName()+" "+getLastName();
	}

	public int compareTo(Employee o) {
		Employee e = (Employee)o;
		if(this.emplyeeCode > e.getEmplyeeCode())
			return 1;
		if(this.emplyeeCode < e.getEmplyeeCode())
			return -1;
		if(this.emplyeeCode == e.getEmplyeeCode())
			return 0;
		return 0;
	}
}

We have created an Employee class which implements the Comparable interface and overrides the compareTo() method. The comparison between the Employee objects is defined by comparing the employeeCode property of the Employee objects. The comparTo() method returns an integer, which tells whether the current employeeCode is greater than, or smaller than or equal to the compared employeeCode. It returns 1, if the current employeeCode is greater than the compared employeeCode, -1 if, the current employeeCode is smaller than the compared employeeCode, else it returns 0 if both are equal. Since, the employeeCode is of type integer, we have compared it using the simple integer comparison operators.

EmployeeFirstNameComparatorImpl.java

 package com.javacodegeeks.entity;

import java.util.Comparator;

public class EmployeeFirstNameComparatorImpl implements Comparator<Employee>{

	@Override
	public int compare(Employee o1, Employee o2) {
		if(o1.getFirstName().compareTo(o2.getFirstName()) > 0){
			return 1;
		}else if(o1.getFirstName().compareTo(o2.getFirstName()) < 0){
			return -1;
		}else{
			return 0;
		}

	}

}

The class implements the Comparator interface of the type Employee and provides the comparison rules by overriding the compare() method. The compare() method takes two arguments of the type Employee and:-
return 1: if o1.getFirstName() is greater than o2.getFirstName().
return -1: if o1.getFirstName() is smaller than o2.getFirstName().
return 0: if o1.getFirstName() is equals to o2.getFirstName().

Please note that the method getFirstName() returns String which implements the Comparable interface. We have used the compareTo() method of the String class to compare the strings.

EmployeeLastNameComparatorImpl.java

 package com.javacodegeeks.entity;

import java.util.Comparator;

public class EmployeeLastNameComparatorImpl implements Comparator<Employee> {

	@Override
	public int compare(Employee o1, Employee o2) {
		if(o1.getLastName().compareTo(o2.getLastName()) > 0){
			return 1;
		}else if(o1.getLastName().compareTo(o2.getLastName()) < 0){
			return -1;
		}else{
			return 0;
		}

	}
}

This class works the same as the above class. But this class compares the objects on the basis of the lastName property of the Employee class. The compare() method takes two arguments of the type Employee and:-
return 1: if o1.getLastName() is greater than o2.getLastName().
return -1: if o1.getLastName() is smaller than o2.getLastName().
return 0: if o1.getLastName() is equals to o2.getLastName().

MergesortObjectExample.java

package com.javacodegeeks.sorting.mergesort;

import com.javacodegeeks.entity.Employee;
import com.javacodegeeks.entity.EmployeeFirstNameComparatorImpl;
import com.javacodegeeks.entity.EmployeeLastNameComparatorImpl;
import com.javacodegeeks.sorting.utility.SortingUtility;

public class MergesortObjectExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Employee []employees = new Employee[5];
		Employee employee = new Employee("John","Carter",5658);
		employees[0] = employee;
		employee = new Employee("Mary","Carter",7412);
		employees[1] = employee;
		employee = new Employee("Alex","Lumb",1158);
		employees[2] = employee;
		employee = new Employee("David","Jhonson",1254);
		employees[3] = employee;
		employee = new Employee("Shaun","Smith",4587);
		employees[4] = employee;

		System.out.println("Sorting in ascending order on basis of employeeCode...\n");
		printArray(employees);
		SortingUtility.sort(employees);
		System.out.println("After sorting...");
		printArray(employees);

		System.out.println("\nSorting in ascending order on basis of employeeFirstName...\n");
		printArray(employees);
		SortingUtility.sort(employees,new EmployeeFirstNameComparatorImpl());
		System.out.println("After sorting...");
		printArray(employees);

		System.out.println("\nSorting in ascending order on basis of employeeLastName...\n");
		printArray(employees);
		SortingUtility.sort(employees,new EmployeeLastNameComparatorImpl());
		System.out.println("After sorting...");
		printArray(employees);

		System.out.println("\nSorting in descending order on basis of employeeCode...\n");
		printArray(employees);
		SortingUtility.sort(employees,SortingUtility.DESC_ORDER);
		System.out.println("After sorting...");
		printArray(employees);

		System.out.println("\nSorting in descending order on basis of employeeFirstName...\n");
		printArray(employees);
		SortingUtility.sort(employees,SortingUtility.DESC_ORDER,new EmployeeFirstNameComparatorImpl());
		System.out.println("After sorting...");
		printArray(employees);

		System.out.println("\nSorting in descending order on basis of employeeLastName...\n");
		printArray(employees);
		SortingUtility.sort(employees,SortingUtility.DESC_ORDER,new EmployeeLastNameComparatorImpl());
		System.out.println("After sorting...");
		printArray(employees);

	}

	public static<T> void printArray(T []a){
		for(T t : a){
			System.out.println(t);
		}
	}

}
  • If we run the above code, we will have the following results:
Sorting in ascending order on basis of employeeCode...

Employee Code: 5658, Name:John Carter
Employee Code: 7412, Name:Mary Carter
Employee Code: 1158, Name:Alex Lumb
Employee Code: 1254, Name:David Jhonson
Employee Code: 4587, Name:Shaun Smith
After sorting...
Employee Code: 1158, Name:Alex Lumb
Employee Code: 1254, Name:David Jhonson
Employee Code: 4587, Name:Shaun Smith
Employee Code: 5658, Name:John Carter
Employee Code: 7412, Name:Mary Carter

Sorting in ascending order on basis of employeeFirstName...

Employee Code: 1158, Name:Alex Lumb
Employee Code: 1254, Name:David Jhonson
Employee Code: 4587, Name:Shaun Smith
Employee Code: 5658, Name:John Carter
Employee Code: 7412, Name:Mary Carter
After sorting...
Employee Code: 1158, Name:Alex Lumb
Employee Code: 1254, Name:David Jhonson
Employee Code: 5658, Name:John Carter
Employee Code: 7412, Name:Mary Carter
Employee Code: 4587, Name:Shaun Smith

Sorting in ascending order on basis of employeeLastName...

Employee Code: 1158, Name:Alex Lumb
Employee Code: 1254, Name:David Jhonson
Employee Code: 5658, Name:John Carter
Employee Code: 7412, Name:Mary Carter
Employee Code: 4587, Name:Shaun Smith
After sorting...
Employee Code: 7412, Name:Mary Carter
Employee Code: 5658, Name:John Carter
Employee Code: 1254, Name:David Jhonson
Employee Code: 1158, Name:Alex Lumb
Employee Code: 4587, Name:Shaun Smith

Sorting in descending order on basis of employeeCode...

Employee Code: 7412, Name:Mary Carter
Employee Code: 5658, Name:John Carter
Employee Code: 1254, Name:David Jhonson
Employee Code: 1158, Name:Alex Lumb
Employee Code: 4587, Name:Shaun Smith
After sorting...
Employee Code: 7412, Name:Mary Carter
Employee Code: 5658, Name:John Carter
Employee Code: 4587, Name:Shaun Smith
Employee Code: 1254, Name:David Jhonson
Employee Code: 1158, Name:Alex Lumb

Sorting in descending order on basis of employeeFirstName...

Employee Code: 7412, Name:Mary Carter
Employee Code: 5658, Name:John Carter
Employee Code: 4587, Name:Shaun Smith
Employee Code: 1254, Name:David Jhonson
Employee Code: 1158, Name:Alex Lumb
After sorting...
Employee Code: 4587, Name:Shaun Smith
Employee Code: 7412, Name:Mary Carter
Employee Code: 5658, Name:John Carter
Employee Code: 1254, Name:David Jhonson
Employee Code: 1158, Name:Alex Lumb

Sorting in descending order on basis of employeeLastName...

Employee Code: 4587, Name:Shaun Smith
Employee Code: 7412, Name:Mary Carter
Employee Code: 5658, Name:John Carter
Employee Code: 1254, Name:David Jhonson
Employee Code: 1158, Name:Alex Lumb
After sorting...
Employee Code: 4587, Name:Shaun Smith
Employee Code: 1158, Name:Alex Lumb
Employee Code: 1254, Name:David Jhonson
Employee Code: 5658, Name:John Carter
Employee Code: 7412, Name:Mary Carter

5. Download the source code

This was an example on Mergesort algorithm in Java. You can download the source code of this example from here:MergesortExample.zip

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of