merge sort

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.

  

posted on 2018-03-11 10:00  野原新之助0 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/chrislyr/p/8543288.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值