How do you take an array for example A = [4 6 7 1 2 5] and sort it from ascending order. So it would output A = [1 2 4 5 6 7]. In MATlab without using the sort function as well.
HI, Please find my implementation of selection sort.
%--------------------------------------------------------------------------
% Syntax: sx = selectionSort(x);
%
% Inputs: x is a vector of length n
%
% Outputs: sx is the sorted (ascending) version of x
%
% Description: This function sorts the input array x in ascending
order
% using the selection sort algorithm
%
% Complexity: O(n^2) best-case performance
% O(n^2) average-case performance
% O(n^2) worst-case performance
% O(1) auxiliary space
%--------------------------------------------------------------------------
% Seletion sort
function x = selectionSort(x)
n = length(x);
for j = 1:(n - 1)
% Find jth smallest element
imin = j;
for i = (j + 1):n
if (x(i) < x(imin))
imin = i;
end
end
% Put jth smallest element in place
if (imin ~= j)
x = swap(x,imin,j);
end
end
end
% Swap x(i) and x(j)
% Note: In practice, x xhould be passed by reference
function x = swap(x,i,j)
val = x(i);
x(i) = x(j);
x(j) = val;
end
Get Answers For Free
Most questions answered within 1 hours.