I am trying to write a program that compares the selection sort function, the bubble sort and insertion sort. I am struggling on the selection sort I know how it works but I cant come up with a code.

3 views (last 30 days)
Kevin Junior on 19 Oct 2013
At the end I have to write a program that compares the three sorting methods I am using extra output C(number of comparisons) and S(number of swaps) to facilitate the comparison. Here is what i have so far,
% Function Bubble sort
function [y,C,S] = Bubble(x)
% x is a column n-vector
%y is a column n-vector obtained by applying the bubble process to x
% C is the number of required comparisons
% S is the number of required swaps
n = length(x); C = 0; S = 0;
for k = n-1:-1:1
C = C + 1;
if x(k+1) < x(k)
t = x(k+1);
x(k+1) = x(k);
x(k) = t;
S = S+1;
end
end
y = x;
% Now full bubbleSort function
function[y,TotalC,TotalS] = Bubblesort(x)
% x is a column n-vector
% y is a column n-vector obtained by permuting the values in x so that they are ordered from smallest to largest
% TotalC is the total number of required comparisons
% TotalS is the total number of required swaps
n = length(x);
TotalC = 0;
TotalS = 0;
k = 1;
while(k==1 || s>0)&& k <=n-1
[x(k:n),C,S] = Bubble(x(k:n));% I am using the bubble function I created above
k = k+1;
TotalC = TotalC + C;
TotalS = TotalS + S;
end
y = x;
% Here comes the selection sort.
%I am using the same format as for the bubble sort
% I create a function select then the full selectsort function using
% the select function
% Select function
function [y,C,S] = Mekuluselect(x)
n = length(x);
C = 0; S = 0;
for k = 1:n
C = C + 1;
m = k;
if x(k) < x(m)
temp = x(k);
x(k) = x(m);
x(m) = temp;
S = S + 1;
end
end
y = x;
end
% Full selection sort function
function [y,TotalC,TotalS] = MekuluselectSort(x)
% x is an n-vector
% y is x with x(1) and x(m) swapped where x(m)
% is the minimum value in x
n = length(x);
TotalC = 0; % Total number of required comparisons
TotalS = 0; % Total number of swaps
for k = 1:n
[x(1:k),C,S] = select(x(1:k));
TotalC = TotalC + C;
TotalS = TotalS + S;
end
y = x;
end