MERGE-SORT: INTRODUCTION TO ALGORITHMS

Merge sort:归并排序


Animation

这里写图片描述
An example of merge sort. First divide the list into the smallest unit (1 element), then compare each element with the adjacent list to sort and merge the two adjacent lists. Finally all the elements are sorted and merged.


这里写图片描述
Merge sort animation. The sorted elements are represented by dots.


这里写图片描述
A recursive merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort (top-down).


Complexity

ClassSorting algorithm
Data structureArray
Worst case performance O(nlogn)
Best case performance O(nlogn) typical, O(n) natural variant
Average case performance O(nlogn)
Worst case space complexity О(n) total, O(n) auxiliary

Pseudo code

MERGE-SORT(A,p,r)
 1  if p<r
 2      q = floor((p+r)/2)
 3      MERGE-SORT(A,p,q)
 4      MERGE-SORT(A,q+1,r)
 5      MERGE(A,p,q,r)

MERGE(A,p,q,r)
 1  n1 = q-p+1
 2  n2 = r-q
 3  let L[1..n1+1] and R[1..n2+1] be new arrays
 4  for i=1 to n1
 5      L[i] = A[p+i-1]
 6  for j=1 to n2
 7      R[j] = A[q+j]
 8  L[n1+1] = Infinite
 9  R[n2+1] = Infinite
10  i = 1
11  j = 1
12  for k=p to r
13      if L[i] <= R[j]
14          A[k] = L[i]
15          i = i+1
16      else
17          A[k] = R[j]
18          j = j+1

Figure

这里写图片描述

这里写图片描述

这里写图片描述


Reference

<< Introduction to Algorithms >> Third Edition, THOMAS H. CORMEN, CHARLES E. LEISERSON, RONALD L. RIVEST, CLIFFORD STEIN.
https://en.wikipedia.org/wiki/Merge_sort

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值