function [x,TotalC,TotalS] = InsertionSortIntervals(x)
% x is a vector of Interval references. Sort x so that its referenced
% Intervals are ordered from narrowest to widest using insertion sort.
% TotalC is the total number of required comparisons.
n = length(x); TotalC = 0; TotalS = 0;
for k = 2:n
[x(1:k),C,S] = Insert(x(1:k));
TotalC = TotalC + C;
TotalS = TotalS + S;
end
function [x,C,S] = Insert(x)
% Pre: x is a length m vector of Intervals references with x(1:m-1)
% ordered from narrowest to widest.
% Post: x is sorted from narrowest to widest using the insert process.
% C is the number of required comparisions.
% S is the number of required swaps.
m = length(x); S = 0;
k = m-1;
while k>=1 && x(k).getWidth()>x(k+1).getWidth()
t = x(k+1);
x(k+1) = x(k);
x(k) = t;
S = S+1;
k = k-1;
end
if k==0
C = S;
else
C = S+1;
end