Q: Given an array of integers, sort the elements in the array in ascending order. The merge sort algorithm should be used to solve this problem.
1 public class Solution { 2 public int[] mergeSort(int[] array) { 3 // Write your solution here 4 if (array == null || array.length == 0) { 5 return array; 6 } 7 int[] helper = new int[array.length]; 8 mergeSort(array, 0, array.length - 1, helper); 9 return array; 10 } 11 12 private void mergeSort(int[] array, int left, int right, int[] helper) { 13 if (left == right) return; 14 int mid = left + (right - left) / 2; 15 mergeSort(array, left, mid, helper); 16 mergeSort(array, mid + 1, right, helper); 17 merge(array, helper, left, mid, right); 18 } 19 20 private void merge(int[] array, int[] helper, int left, int mid, int right) { 21 for (int i = left; i <= right; i++) { 22 helper[i] = array[i]; 23 } 24 int lp = left; 25 int rp = mid + 1; 26 int pin = left; 27 while (lp <= mid && rp <= right) { 28 if (helper[lp] < helper[rp]) { 29 array[pin++] = helper[lp++]; 30 } else { 31 array[pin++] = helper[rp++]; 32 } 33 } 34 while (lp <= mid) { 35 array[pin++] = helper[lp++]; 36 } 37 } 38 }
High level description:
Basicly, use merge() to merge two short sorted array into one long sorted array.
Use post-order recursion to divide the problem into smallest pieces.
base case is when left index == right index.
sub-problem is to find mid index of current array and divide it into two.
post-order process, merge the two sorted array into one sorted array.
Time complexity: O(n) for divide process, O(nlogn) for merge.
Space complexity: call stack O(logn), additional cost O(n) -- for helper array.
Basic sorting algorithm.