The Merge Sort
dd
We now turn our attention to using a divide and conquer strategy as a way to improve the performance of sorting algorithms. The first algorithm we will study is the merge sort. Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a merge sort on both halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed. Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list. Figure 10 shows our familiar example list as it is being split by mergeSort
. Figure 11 shows the simple lists, now sorted, as they are merged back together.
The mergeSort
function shown in ActiveCode 1 begins by asking the base case question. If the length of the list is less than or equal to one, then we already have a sorted list and no more processing is necessary. If, on the other hand, the length is greater than one, then we use the Python slice
operation to extract the left and right halves. It is important to note that the list may not have an even number of items. That does not matter, as the lengths will differ by at most one.
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
0 comments Comments
Leave a comment
 Basic Data Structures

Objectives

What Are Linear Structures?

What is a Stack?

The Stack Abstract Data Type

Implementing a Stack in Python

What Is a Queue?

The Queue Abstract Data Type

Implementing a Queue in Python

What Is a Deque?

The Deque Abstract Data Type

Implementing a Deque in Python

Lists

The Unordered List Abstract Data Type

Implementing an Unordered List: Linked Lists

The Ordered List Abstract Data Type

Implementing an Ordered List

Vocabulary and Definitions

 Sorting and Searching
 Trees and Tree Algorithms
 Graphs and Graph Algorithms