Skip to content

Commit e2d6f46

Browse files
authored
Merge pull request #21 from MatteoRaso/master
Added the insertion sorting algorithm
2 parents adffaf6 + 69f61cf commit e2d6f46

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

algorithms/sorting/insertion_sort.m

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
%A MATLAB/Octave implementation of the insertion sort algorithm.
2+
%The basic premise is that the program checks whether two neighbouring elements
3+
%in an array are in order and sorts them. It does length(array) number of
4+
% passes. For further details and pseudocode, refer to
5+
%https://en.wikipedia.org/wiki/Insertion_sort
6+
%Note that this function differs slightly from the pseudocode because of
7+
%how MATLAB/Octave arrays start at index 1.
8+
%Note: this function is for educational purposes only.
9+
%You will want to use the built-in sort function for actual coding,
10+
%as it is much more efficent.
11+
function y = insertion_sort(array)
12+
i = 1;
13+
%Assigning the length to a variable should make the program slightly faster.
14+
len = length(array);
15+
while i < len + 1
16+
j = i;
17+
while j > 1 && array(j - 1) > array(j)
18+
%Swapping array(j - 1) and array(j)
19+
temp = array(j - 1);
20+
array(j - 1) = array(j);
21+
array(j) = temp;
22+
j = j - 1;
23+
endwhile
24+
i = i + 1;
25+
endwhile
26+
y = array;
27+
endfunction

0 commit comments

Comments
 (0)