File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments