Logic Visualizer | Python

Merge Sort Algorithm Visualization

Explore the visualization of Merge Sort algorithm through a flowchart and pseudocode, showcasing the recursive divide-and-conquer sorting process.


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

Flowchart Representation

graph TD
    A(Start) --> B{len(arr) <= 1}
    B -- No --> C[mid = len(arr) // 2]
    C -- Merge Sort(arr[:mid]) --> D
    D -- Merge Sort(arr[mid:]) --> E
    E -- Merge --> F
    F -- Result --> G
    G(End)

    B -- Yes --> G(End)

Pseudocode Representation

Start
if len(arr) <= 1:
    return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)

Merge(left, right)
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
    if left[i] < right[j]:
        result.append(left[i])
        i = i + 1
    else:
        result.append(right[j])
        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)

Annotations

  • The algorithm starts with merge_sort function, which recursively divides the array into smaller subarrays until each subarray has only one element. It then merges these subarrays in a sorted manner using the merge function.
  • The merge function compares elements from the left and right subarrays and merges them in sorted order.
  • Key variables like mid, left, right, result, i, and j are used to keep track of indices and subarrays during the sorting and merging process.
  • The algorithm effectively utilizes recursion to divide and conquer the sorting process, ensuring a sorted final array is returned.

By visualizing the merge sort algorithm using the provided flowchart and pseudocode, the logic behind sorting an array using this efficient divide-and-conquer approach becomes clearer and more accessible.

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

Explore the visualization of Merge Sort algorithm through a flowchart and pseudocode, showcasing the recursive divide-and-conquer sorting process.