0% found this document useful (0 votes)
28 views2 pages

Merger Sort Pseudocode

The document outlines the merge sort algorithm, which recursively divides an array into halves until each subarray contains a single element. It then merges the sorted subarrays back together in the correct order. The process involves creating temporary arrays for the left and right halves and merging them based on their values.

Uploaded by

Khushi Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views2 pages

Merger Sort Pseudocode

The document outlines the merge sort algorithm, which recursively divides an array into halves until each subarray contains a single element. It then merges the sorted subarrays back together in the correct order. The process involves creating temporary arrays for the left and right halves and merging them based on their values.

Uploaded by

Khushi Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

FUNCTION mergeSort(arr, left, right)

IF left < right THEN

mid = (left + right) / 2 // Calculate the mid index

// Recursively sort the left half

mergeSort(arr, left, mid)

// Recursively sort the right half

mergeSort(arr, mid + 1, right)

// Merge the sorted halves

merge(arr, left, mid, right)

FUNCTION merge(arr, left, mid, right)

n1 = mid - left + 1 // Size of the left subarray

n2 = right - mid // Size of the right subarray

// Create temporary arrays

DECLARE leftArray[n1]

DECLARE rightArray[n2]

// Copy data to leftArray

FOR i FROM 0 TO n1 - 1 DO

leftArray[i] = arr[left + i]

// Copy data to rightArray

FOR j FROM 0 TO n2 - 1 DO

rightArray[j] = arr[mid + 1 + j]

i = 0 // Initial index for leftArray

j = 0 // Initial index for rightArray


k = left // Initial index for merged array

// Merge the temporary arrays back into arr

WHILE i < n1 AND j < n2 DO

IF leftArray[i] <= rightArray[j] THEN

arr[k] = leftArray[i] // Add the smaller element to arr

i=i+1

ELSE

arr[k] = rightArray[j] // Add the smaller element to arr

j=j+1

k=k+1

// Copy remaining elements of leftArray (if any)

WHILE i < n1 DO

arr[k] = leftArray[i]

i=i+1

k=k+1

// Copy remaining elements of rightArray (if any)

WHILE j < n2 DO

arr[k] = rightArray[j]

j=j+1

k=k+1

You might also like