function [x,TotalC,TotalS] = BubbleSort(x)
% Sort x in ascending order using bubble sort.
% x is a column n-vector.
% 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));
    k = k+1;
    TotalC = TotalC + C;
    TotalS = TotalS + S;
end

function [x,C,S] = Bubble(x)
% Apply the Bubble process to x. 
% Pre:  x is a column n-vector.
% Post: x(1) is the smallest value in x.
% C is the number of required comparisions.
% 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