In: Computer Science
IN MATLAB!!
Q6. Create a 1D array of numbers and implement ‘Merge Sort’ in MATLAB to sort it in ascending order
MATLAB Code:
File: MergeSort.m
function sortedArray = MergeSort(arr)
% Function that sorts the array using MergeSort
len = length(arr);
% Checking length
if len <= 1
% Storing sorted array
sortedArray = arr;
else
% Calling merge function + Recursive Call
sortedArray = Merge(MergeSort(arr(1:round(len/2))),
MergeSort(arr((round(len/2)+1):len)));
end % If end
end % Function end
File: Merge.m
function mArr = Merge(arr1, arr2)
% Helper function for MergeSort
% Calculatint total length
len = length(arr1) + length(arr2);
% Filling with zeros
mArr = zeros(1, len);
% Creating arrays
arr1 = [arr1, inf];
arr2 = [arr2, inf];
% Index values
idxArr1 = 1; idxArr2 = 1;
% Looping over array
for i = 1:len
% Comparing elements
if arr1(idxArr1) < arr2(idxArr2)
% Updating arrays
mArr(i) = arr1(idxArr1);
% Incrementing index
idxArr1 = idxArr1 + 1;
else
% Updating arrays
mArr(i) = arr2(idxArr2);
% Incrementing index
idxArr2 = idxArr2 + 1;
end % If end
end % for end
end % function end
File: mergeSortScript.m
% Script that implements MergeSort
% Creating a 1D array
arr = [95, 57, 35, 37, 3, 12];
fprintf("\nBefore Sort: ");
disp(arr);
% Calling MergeSort function
arr = MergeSort(arr);
fprintf("\nAfter Sort: ");
disp(arr);
______________________________________________________________________________________
Sample Run: