Merge Sort

Java Programming

Java Programming Examples

import java.io.*;

class sort {
	int list[];

	/* Constructor of the class */
	sort(int ... array) {
		list = new int[array.length-1];
		list = array;
		merge(0,array.length-1);
		display();
	}
										
	void merge(int start, int end) {
		if(start < end) {
			int center = (start + end) /2;
			merge(start, center);
			merge(center + 1, end);
			mersrt(start, center, end);
		}
	}
										
	void mersrt(int start,int center, int end) {
		int swap[] = new int[end + 1];
		int i = start;
		int l = start;
		int m = center + 1;
		swap = list;
		while(i <= center && m <= end) {
			if (swap[i] <= swap[m]) {
				list[l] = swap[i];
				i++;
			}
			else {
				list[l] = swap[m];
				m++;
			}
			l++;
		}
		while (i <= center) {
			list[l] = swap[i];
			l++;
			i++;
		}
	}
										
	void display() {
		System.out.println("Sorted array:");
		for(int k:list)
			System.out.println(k);
	}
}
										
class mergesort {
	public static void main(String args[ ]) {
		new sort(6,2,4,1,3,0,5,8,7,9);
	}
}


          /****** Output ******/
          

Sorted array:


0


1


2


3


4


5


6


7


8


9

Learn more about Merge Sort