Python Merge Sorting Algorithm example, python Algorithm
This example describes the Merge Sorting Algorithm implemented by Python. We will share this with you for your reference. The details are as follows:
Merge Sorting is an effective Sorting Algorithm Based on merge operations. This algorithm is a typical application of Divide and Conquer.
Merges ordered subsequences to obtain a fully ordered sequence. That is, first orders each subsequence, and then orders the subsequence segments. If two ordered tables are merged into an ordered table, it is called a two-way merge.
The Python implementation code is as follows:
#-*- coding: UTF-8 -*-import numpy as npdef Merge(a, f, m, l): i = f j = m + 1 tmp = [] while i <= m and j <= l: if a[i] <= a[j]: tmp.append(a[i]) i += 1 else: tmp.append(a[j]) j += 1 while i <= m: tmp.append(a[i]) i += 1 while j<= l: tmp.append(a[j]) j+= 1 i = f for x in xrange(0, len(tmp)): a[i] = tmp[x] i += 1def MergeSort(a, f, l): if f< l: m = (l + f) / 2 MergeSort(a, f, m) MergeSort(a, m+1, l) Merge(a, f, m, l)if __name__ == '__main__': a = np.random.randint(0, 10, size = 10) print "Before sorting..." print "---------------------------------------------------------------" print a print "---------------------------------------------------------------" MergeSort(a, 0, a.size-1) print "After sorting..." print "---------------------------------------------------------------" print a print "---------------------------------------------------------------"
Running result: