MERGE-SORT: INTRODUCTION TO ALGORITHMS

来源:互联网 发布:js判断滚动条位置 编辑:程序博客网 时间:2024/05/18 00:23

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

Class Sorting algorithm Data structure Array 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] = Infinite10  i = 111  j = 112  for k=p to r13      if L[i] <= R[j]14          A[k] = L[i]15          i = i+116      else17          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

0 0