【Python排序搜索基本算法】之归并排序&分治法(Merge Sort and Divide & Conquer)
2013-07-14 21:50
791 查看
Merge Sort is a good introduction to divide & conquer.
The Big O of Merge Sort Algorithm is O(nlog(n)).
The divide & conquer Paradigm
1. Divide into small subproblems
2. Conquer via recursive calls
3. Combine solutions of subproblems into one for the original problem
python code:
The Big O of Merge Sort Algorithm is O(nlog(n)).
The divide & conquer Paradigm
1. Divide into small subproblems
2. Conquer via recursive calls
3. Combine solutions of subproblems into one for the original problem
python code:
def merge(l, r): final = [] while l and r: if l[0] <= r[0]: final.append(l.pop(0)) # add the smaller integer into the new list and delete it from the original list which is similar else: # to the pointer operation of C/C++ final.append(r.pop(0)) return final+l+r def mergeSort(List): #recursive function if len(List) <= 1: return List #The last layer of recursion tree whose element is a single integer else: mid = int(len(List)/2) sorted_left = mergeSort(List[:mid]) #split the whole list of integers into left part and right part sorted_right = mergeSort(List[mid:]) return merge(sorted_left, sorted_right) #merge function which is to merge the two parts each of which has already sorted if __name__ == '__main__': f = open('IntegerArray.txt') number = [] _number = list(f) for n in _number: number.append(int(n)) result = mergeSort(number) print(result)
相关文章推荐
- Python排序搜索基本算法之冒泡排序实例分析
- 【Python排序搜索基本算法】之插入排序
- 【Python排序搜索基本算法】之深度优先搜索、广度优先搜索、拓扑排序、强联通&Kosaraju算法
- 【Python排序搜索基本算法】之深度优先搜索、广度优先搜索、拓扑排序、强联通&Kosaraju算法
- 【Python排序搜索基本算法】之拓扑排序
- Python排序搜索基本算法之堆排序实例详解
- 【Python排序搜索基本算法】之无向图的最小割&Karger算法(Graphs and Minimum Cuts & Karger's Min-Cut Algorithm)
- 【Python排序搜索基本算法】之插入排序
- 【Python排序搜索基本算法】之Dijkstra算法
- 【Python排序搜索基本算法】之拓扑排序
- 【Python排序搜索基本算法】之希尔排序
- 【Python排序搜索基本算法】之Dijkstra最短路径算法(Dijkstra's Shortest-Path Algorithm)
- 【Python排序搜索基本算法】之选择排序
- 【Python排序搜索基本算法】之快速排序(QuickSort)
- 【Python排序搜索基本算法】之Prim算法
- 【Python排序搜索基本算法】之冒泡排序
- Python排序搜索基本算法之希尔排序实例分析
- 【Python排序搜索基本算法】之归并排序
- 【Python排序搜索基本算法】之二叉树的遍历
- 【Python排序搜索基本算法】之Prim算法