
- Java Data Structures Resources
- Java Data Structures - Quick Guide
- Java Data Structures - Resources
- Java Data Structures - Discussion
Java Data Structures - Merge Sort
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being (n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.
Step 1: if it is only one element in the list it is already sorted, return. Step 2: divide the list recursively into two halves until it can no more be divided. Step 3: merge the smaller lists into new list in sorted order.
Example
import java.util.Arrays; public class MergeSort { int[] array = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 }; public void merge(int low, int mid, int high) { int l1, l2, i, b[] = new int[array.length]; for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(array[l1] <= array[l2]) { b[i] = array[l1++]; } else b[i] = array[l2++]; } while(l1 <= mid) { b[i++] = array[l1++]; } while(l2 <= high) { b[i++] = array[l2++]; } for(i = low; i <= high; i++) { array[i] = b[i]; } } public void sort(int low, int high) { int mid; if(low < high) { mid = (low + high) / 2; sort(low, mid); sort(mid+1, high); merge(low, mid, high); } else { return; } } public static void main(String args[]) { MergeSort obj = new MergeSort(); int max = obj.array.length-1; System.out.println("Contents of the array before sorting : "); System.out.println(Arrays.toString(obj.array)); obj.sort(0, max); System.out.println("Contents of the array after sorting : "); System.out.println(Arrays.toString(obj.array)); } }
Output
[10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0] Contents of the array after sorting : [0, 10, 14, 19, 26, 27, 31, 33, 35, 42, 44]
Advertisements