You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers merge sort and quick sort — two efficient, divide-and-conquer sorting algorithms in the OCR A-Level Computer Science (H446) specification. These algorithms are significantly faster than bubble sort and insertion sort for large data sets.
Both merge sort and quick sort use the divide and conquer strategy:
Merge sort works by:
function mergeSort(data)
if data.length <= 1 then
return data
endif
mid = data.length DIV 2
left = mergeSort(data[0..mid-1])
right = mergeSort(data[mid..data.length-1])
return merge(left, right)
endfunction
function merge(left, right)
result = []
i = 0
j = 0
while i < left.length AND j < right.length
if left[i] <= right[j] then
result.append(left[i])
i = i + 1
else
result.append(right[j])
j = j + 1
endif
endwhile
// Append remaining elements
while i < left.length
result.append(left[i])
i = i + 1
endwhile
while j < right.length
result.append(right[j])
j = j + 1
endwhile
return result
endfunction
def merge_sort(data):
if len(data) <= 1:
return data
mid = len(data) // 2
left = merge_sort(data[:mid])
right = merge_sort(data[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
Sort [6, 3, 8, 1, 5, 2, 7, 4]:
Division phase:
[6, 3, 8, 1, 5, 2, 7, 4]
/ \
[6, 3, 8, 1] [5, 2, 7, 4]
/ \ / \
[6, 3] [8, 1] [5, 2] [7, 4]
/ \ / \ / \ / \
[6] [3] [8] [1] [5] [2] [7] [4]
Merge phase:
[6] [3] [8] [1] [5] [2] [7] [4]
\ / \ / \ / \ /
[3, 6] [1, 8] [2, 5] [4, 7]
\ / \ /
[1, 3, 6, 8] [2, 4, 5, 7]
\ /
[1, 2, 3, 4, 5, 6, 7, 8]
| Case | Complexity | Explanation |
|---|---|---|
| Best | O(n log n) | Always divides and merges |
| Worst | O(n log n) | Always divides and merges |
| Average | O(n log n) | Always divides and merges |
Quick sort works by:
function quickSort(data, low, high)
if low < high then
pivotIndex = partition(data, low, high)
quickSort(data, low, pivotIndex - 1)
quickSort(data, pivotIndex + 1, high)
endif
endfunction
function partition(data, low, high)
pivot = data[high]
i = low - 1
for j = low to high - 1
if data[j] <= pivot then
i = i + 1
swap data[i] and data[j]
endif
next j
swap data[i + 1] and data[high]
return i + 1
endfunction
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.