Python Merge Sort

Document 对象参考手册Python3 Examples

Merge sort (or mergesort) is an efficient sorting algorithm based on the merge operation. This algorithm is a very typical application of the divide and conquer (Divide and Conquer) method.

Divide and Conquer:

  • Divide: Recursively divide the current sequence into two halves equally.
  • Integrate: Integrate the subsequences obtained in the previous step together (merge) while maintaining the order of elements.

Example

def merge(arr, l, m, r): n1 = m - l + 1 n2 = r- m # Create temporary arrays L = [0] * (n1) R = [0] * (n2) # Copy data to temporary arrays L[] and R[] for i in range(0 , n1): L[i] = arr[l + i] for j in range(0 , n2): R[j] = arr[m + 1 + j] # Merge the temporary arrays into arr[l..r] i = 0 # Initialize the index of the first subarray j = 0 # Initialize the index of the second subarray k = l # Initialize the index of the merged subarray while i < n1 and j < n2 : if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Copy the remaining elements of L[] while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[] while j < n2: arr[k] = R[j] j += 1 k += 1 def mergeSort(arr,l,r): if l < r: m = int((l+(r-1))/2) mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) arr = [12, 11, 13, 5, 6, 7] n = len(arr) print ("Given array") for i in range(n): print ("%d" %arr[i]), mergeSort(arr,0,n-1) print ("\n\nSorted array") for i in range(n): print ("%d" %arr[i]),

Executing the above code produces the following output:

给定的数组
12
11
13
5
6
7


排序后的数组
5
6
7
11
12
13

Document 对象参考手册Python3 Examples

Other Extensions