Logic Visualizer | Python

Merge Sort Visualization

Analyze and understand the merge sort algorithm through visual representation, pseudocode explanation, and step-by-step annotations.


Empty image or helper icon

Prompt

def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[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

arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print(sorted_arr)

Answer

Visual Representation of Merge Sort Algorithm

Pseudocode Representation

function merge_sort(arr)
    if length of arr <= 1
        return arr
    mid = length of arr divided by 2
    left = merge_sort(first half of arr)
    right = merge_sort(second half of arr)
    return merge(left, right)

function merge(left, right)
    create an empty list called result
    initialize variables i and j to 0
    while i < length of left and j < length of right
        if left[i] < right[j]
            append left[i] to result
            increment i by 1
        else
            append right[j] to result
            increment j by 1
    extend result with remaining elements in left and right
    return result

arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print sorted_arr

Annotations

  1. The algorithm starts with the merge_sort function that recursively divides the input array into halves until each sub-array has only one element.

  2. The merge function then merges the sorted sub-arrays back together in the correct order.

  3. The merging process compares elements from the left and right sub-arrays, appending the smaller element first to the result list.

  4. The final result list is created by extending it with the remaining elements from both sub-arrays.

  5. The sorted array is then returned and printed.

This visualization simplifies the sorting process, showcasing how the merge sort algorithm divides and conquers the input array to ultimately merge the sorted sub-arrays.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

Analyze and understand the merge sort algorithm through visual representation, pseudocode explanation, and step-by-step annotations.