Sorting algorithms/Insertion sort: Difference between revisions
(→{{header|Perl}}: Rather not use a statement label if I can help it) |
(→{{header|C}}: Keep indexing the same as the shell sort) |
||
Line 195:
for (i = 1; i < n; i++) {
k = a[i];
for (j = i
a[j
}
a[j
}
}
|
Revision as of 00:46, 18 March 2011
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
Heap sort | Merge sort | Patience sort | Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Insertion sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |
An O(n2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part.
Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases (i) small n, (ii) as the final finishing-off algorithm for O(n logn) algorithms such as mergesort and quicksort.
The algorithm is as follows (from the wikipedia):
function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value done
Writing the algorithm for integers will suffice.
ActionScript
<lang ActionScript>function insertionSort(array:Array) { for(var i:int = 1; i < array.length;i++) { var value = array[i]; var j:int = i-1; while(j >= 0 && array[j] > value) { array[j+1] = array[j]; j--; } array[j+1] = value; } return array; }</lang>
Ada
<lang ada>type Data_Array is array(Natural range <>) of Integer;
procedure Insertion_Sort(Item : in out Data_Array) is
First : Natural := Item'First; Last : Natural := Item'Last; Value : Integer; J : Integer;
begin
for I in (First + 1)..Last loop Value := Item(I); J := I - 1; while J in Item'range and then Item(J) > Value loop Item(J + 1) := Item(J); J := J - 1; end loop; Item(J + 1) := Value; end loop;
end Insertion_Sort;</lang>
ALGOL 68
<lang algol68>MODE DATA = REF CHAR;
PROC in place insertion sort = (REF[]DATA item)VOID: BEGIN
INT first := LWB item; INT last := UPB item; INT j; DATA value; FOR i FROM first + 1 TO last DO value := item[i]; j := i - 1; # WHILE j >= LWB item AND j <= UPB item ANDF item[j] > value DO // example of ANDF extension # WHILE ( j >= LWB item AND j <= UPB item | item[j]>value | FALSE ) DO # no extension! # item[j + 1] := item[j]; j -:= 1 OD; item[j + 1] := value OD
END # in place insertion sort #;
[32]CHAR data := "big fjords vex quick waltz nymph"; [UPB data]DATA ref data; FOR i TO UPB data DO ref data[i] := data[i] OD; in place insertion sort(ref data); FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line); print((data))</lang> Output:
abcdefghiijklmnopqrstuvwxyz big fjords vex quick waltz nymph
AutoHotkey
contributed by Laszlo on the ahk forum <lang AutoHotkey>MsgBox % InsertionSort("") MsgBox % InsertionSort("xxx") MsgBox % InsertionSort("3,2,1") MsgBox % InsertionSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z")
InsertionSort(var) { ; SORT COMMA SEPARATED LIST
StringSplit a, var, `, ; make array, size = a0 Loop % a0-1 { i := A_Index+1, v := a%i%, j := i-1 While j>0 and a%j%>v u := j+1, a%u% := a%j%, j-- u := j+1, a%u% := v } Loop % a0 ; construct string from sorted array sorted .= "," . a%A_Index% Return SubStr(sorted,2) ; drop leading comma
}</lang>
AWK
Sort standard input (storing lines into an array) and output to standard output <lang awk>{
line[NR] = $0
} END { # sort it with insertion sort
for(i=1; i <= NR; i++) { value = line[i] j = i - 1 while( ( j > 0) && ( line[j] > value ) ) { line[j+1] = line[j] j-- } line[j+1] = value } #print it for(i=1; i <= NR; i++) { print line[i] }
}</lang>
BASIC
This version should work on any BASIC that can accept arrays as function arguments. <lang qbasic>DECLARE SUB InsertionSort (theList() AS INTEGER)
DIM n(10) AS INTEGER, L AS INTEGER, o AS STRING FOR L = 0 TO 10
n(L) = INT(RND * 32768)
NEXT InsertionSort n() FOR L = 1 TO 10
PRINT n(L); ";";
NEXT
SUB InsertionSort (theList() AS INTEGER)
DIM insertionElementIndex AS INTEGER FOR insertionElementIndex = 1 TO UBOUND(theList) DIM insertionElement AS INTEGER insertionElement = theList(insertionElementIndex) DIM j AS INTEGER j = insertionElementIndex - 1 DO WHILE (j >= 0) 'necessary for BASICs without short-circuit evaluation IF (insertionElement < theList(j)) THEN theList(j + 1) = theList(j) j = j - 1 ELSE EXIT DO END IF LOOP theList(j + 1) = insertionElement NEXT
END SUB</lang>
Sample output:
1486 ; 9488 ; 9894 ; 17479 ; 18989 ; 23119 ; 23233 ; 24927 ; 25386 ; 26689 ;
BBC BASIC
<lang BBCBASIC>DEF PROC_InsertionSort(Size%) FOR I%=2 TO Size%
Temp%=data%(I%) J%=I% WHILE J%>1 AND Temp%<data%(J%-1) data%(J%)=data%(J%-1) J%=J%-1 ENDWHILE IF J% <> I% data%(J%)=Temp%
NEXT I% ENDPROC</lang>
C
<lang c> void insertion_sort (int *a, int n) {
int i, j, k; for (i = 1; i < n; i++) { k = a[i]; for (j = i; j > 0 && k < a[j - 1]; j--) { a[j] = a[j - 1]; } a[j] = k; }
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; insertion_sort(a, n); return 0;
} </lang>
C++
Uses binary search via std::upper_bound() to find the insertion position in logarithmic time, then performs the insertion via std::rotate(), in linear time.
<lang cpp>#include <algorithm>
template<typename Iter> void insertion_sort(Iter beg, Iter end) {
for (Iter i = beg; i != end; ++i) std::rotate(std::upper_bound(beg, i, *i), i, i+1);
}</lang>
C#
<lang csharp>using System;
namespace insertionsort {
class Program { static void Main(string[] args) { int[] A = new int[] { 3, 9, 4, 6, 8, 1, 7, 2, 5 }; insertionSort(ref A); Console.WriteLine(string.Join(",", A)); }
public static void insertionSort (ref int[] A){ for (int i = 0; i < A.Length; i++) { int value = A[i], j = i-1; while (j >= 0 && A[j] > value) { A[j + 1] = A[j]; j--; } A[j + 1] = value; } } }
} </lang>
Clojure
Translated from the Haskell example: <lang lisp>(defn in-sort! [data]
(letfn [(insert ([raw x](insert [] raw x))
([sorted [y & raw] x] (if (nil? y) (conj sorted x) (if (<= x y ) (concat sorted [x,y] raw) (recur (conj sorted y) raw x )))))]
(reduce insert [] data)))
- Usage
- (in-sort! [6,8,5,9,3,2,1,4,7])
- Returns
- [1 2 3 4 5 6 7 8 9]</lang>
COBOL
This exerpt contains just enough of the procedure division to show the sort itself. The appropriate data division entries can be inferred. See also the entry for the Bubble sort for a full program. <lang COBOL> C-PROCESS SECTION.
PERFORM E-INSERTION VARYING WB-IX-1 FROM 1 BY 1 UNTIL WB-IX-1 > WC-SIZE.
...
E-INSERTION SECTION. E-000. MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP. SET WB-IX-2 TO WB-IX-1.
PERFORM F-PASS UNTIL WB-IX-2 NOT > 1 OR WC-TEMP NOT < WB-ENTRY(WB-IX-2 - 1).
IF WB-IX-1 NOT = WB-IX-2 MOVE WC-TEMP TO WB-ENTRY(WB-IX-2).
E-999. EXIT.
F-PASS SECTION. F-000. MOVE WB-ENTRY(WB-IX-2 - 1) TO WB-ENTRY(WB-IX-2). SET WB-IX-2 DOWN BY 1.
F-999. EXIT.</lang>
Common Lisp
<lang lisp>(defun span (predicate list)
(let ((tail (member-if-not predicate list))) (values (ldiff list tail) tail)))
(defun less-than (x)
(lambda (y) (< y x)))
(defun insert (list elt)
(multiple-value-bind (left right) (span (less-than elt) list) (append left (list elt) right)))
(defun insertion-sort (list)
(reduce #'insert list :initial-value nil))</lang>
D
<lang d>import std.stdio, std.algorithm;
void insertionSort(Range)(Range data) {
foreach (i; 1 .. data.length) { auto value = data[i]; int j = i - 1; while (j >= 0 && data[j] > value) { data[j + 1] = data[j]; j--; } data[j + 1] = value; }
}
void main() {
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; insertionSort(array); writeln(array);
}</lang> Output:
[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]
E
A direct conversion of the pseudocode.
<lang e>def insertionSort(array) {
for i in 1..!(array.size()) { def value := array[i] var j := i-1 while (j >= 0 && array[j] > value) { array[j + 1] := array[j] j -= 1 } array[j+1] := value }
}</lang>
Test case:
<lang e>? def a := [71, 53, 22, 24, 83, 54, 39, 78, 65, 26, 60, 75, 67, 27, 52, 59, 93, 62, 85, 99, 88, 10, 91, 85, 13, 17, 14, 96, 55, 10, 61, 94, 27, 50, 75, 40, 47, 63, 10, 23].diverge() > insertionSort(a) > a
- value: [10, 10, 10, 13, 14, 17, 22, 23, 24, 26, 27, 27, 39, 40, 47, 50, 52, 53, 54, 55, 59, 60, 61, 62, 63, 65, 67, 71, 75, 75, 78, 83, 85, 85, 88, 91, 93, 94, 96, 99].diverge()</lang>
Eiffel
This solution is shown in the routine sort
of the class MY_SORTED_SET
.
For a more complete explanation of the Eiffel sort examples, see the Bubble sort.
<lang eiffel>class
MY_SORTED_SET [G -> COMPARABLE]
inherit
TWO_WAY_SORTED_SET [G] redefine sort end
create
make
feature
sort -- Insertion sort local l_j: INTEGER l_value: like item do across 2 |..| count as ii loop from l_j := ii.item - 1 l_value := Current.i_th (ii.item) until l_j < 1 or Current.i_th (l_j) <= l_value loop Current.i_th (l_j + 1) := Current.i_th (l_j) l_j := l_j - 1 end Current.i_th (l_j + 1) := l_value end end
end</lang>
Emacs Lisp
<lang lisp>
(defun min-or-max-of-2-numbers (n1 n2 rel)
"n1 and n2 are two numbers, rel can be '< or '> according to
what sort of sorting is wanted, this function returns the greater or smaller number n1 or n2"
(cond ((eval (list rel n1 n2)) n1) (t n2)))
(defun min-or-max-of-a-list (lon rel)
"lon is a list of numbers, rel is '< or '>, this fonction
returns the higher or lower number of the list"
(if (cdr lon) (min-or-max-of-2-numbers (car lon)
(min-or-max-of-a-list (cdr lon) rel) rel)
(car lon)))
(defun remove-number-from-list (n lon)
"lon is a list of numbers, n is a number belonging to the list,
this function returns the same list but the number n. If n is present twice or more, it will be removed only once"
(if lon (cond ((= (car lon) n) (cdr lon)) (t (cons (car lon) (remove-number-from-list n (cdr lon))))) nil))
(defun sort-insertion (lon rel)
"lon is a list of numbers, rel can be '< or '>, this function
returns a list containing the same elements but which is sorted according to rel"
(if lon (cons (min-or-max-of-a-list lon rel)
(sort-insertion (remove-number-from-list (min-or-max-of-a-list lon rel) lon) rel))
nil))
- let's try it
(sort-insertion (list 1 2 3 9 8 7 25 12 3 2 1) '>)
</lang>
Erlang
<lang Erlang>-module(sort). -export([insertion/1]).
insertion(L) -> lists:foldl(fun insert/2, [], L).
insert(X,[]) -> [X]; insert(X,L=[H|_]) when X =< H -> [X|L]; insert(X,[H|T]) -> [H|insert(X, T)].</lang>
And the calls: <lang erlang>1> c(sort). {ok,sort} 2> sort:insertion([5,3,9,4,1,6,8,2,7]). [1,2,3,4,5,6,7,8,9]</lang>
Forth
<lang forth>: insert ( start end -- start )
dup @ >r ( r: v ) \ v = a[i] begin 2dup < \ j>0 while r@ over cell- @ < \ a[j-1] > v while cell- \ j-- dup @ over cell+ ! \ a[j] = a[j-1] repeat then r> swap ! ; \ a[j] = v
- sort ( array len -- )
1 ?do dup i cells + insert loop drop ;
create test 7 , 3 , 0 , 2 , 9 , 1 , 6 , 8 , 4 , 5 , test 10 sort test 10 cells dump</lang>
Fortran
In ANSI FORTRAN 77 and above with MIL-STD 1753 extensions, use structured DO and DO WHILE loops <lang fortran>SUBROUTINE Insertion_Sort(a)
REAL, INTENT(in out), DIMENSION(:) :: a REAL :: temp INTEGER :: i, j DO i = 2, SIZE(a) j = i - 1 temp = a(i) DO WHILE (j>=1 .AND. a(j)>temp) a(j+1) = a(j) j = j - 1 END DO a(j+1) = temp END DO
END SUBROUTINE Insertion_Sort</lang> In ISO Fortran 90 and above the intrinsic function CSHIFT can be used to shift the elements in the array but in practice is slower than the above example <lang fortran>DO i = 2, SIZE(a)
j = i - 1 DO WHILE (j>=1 .AND. a(j) > a(i)) j = j - 1 END DO a(j+1:i) = cshift(a(j+1:i),-1)
END DO</lang>
GAP
<lang gap>InsertionSort := function(L)
local n, i, j, x; n := Length(L); for i in [ 2 .. n ] do x := L[i]; j := i - 1; while j >= 1 and L[j] > x do L[j + 1] := L[j]; j := j - 1; od; L[j + 1] := x; od;
end;
s := "BFKRIMPOQACNESWUTXDGLVZHYJ"; InsertionSort(s); s;
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ"</lang>
Go
<lang go>package main
import "fmt"
func main() {
var list insert = []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list)
list.sort() fmt.Println("sorted! ", list)
}
type insert []int
func (a insert) sort() {
for i := 1; i < len(a); i++ { value := a[i] j := i - 1 for j >= 0 && a[j] > value { a[j+1] = a[j] j = j - 1 } a[j+1] = value }
}</lang> Output:
unsorted: [31 41 59 26 53 58 97 93 23 84] sorted! [23 26 31 41 53 58 59 84 93 97]
Groovy
Solution: <lang groovy>def insertionSort = { list ->
def size = list.size() (1..<size).each { i -> def value = list[i] def j = i - 1 for (; j >= 0 && list[j] > value; j--) { print "."; list[j+1] = list[j] } print "."; list[j+1] = value } list
}</lang>
Test: <lang groovy>println (insertionSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) println (insertionSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))</lang>
Output:
..................................................................................................................................................................[4, 12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99] ...............................................................................................................................................................[0, 1, 4, 5, 7, 8, 12, 14, 18, 20, 31, 33, 44, 62, 70, 73, 75, 76, 78, 81, 82, 84, 88]
Haskell
<lang haskell>import Data.List (insert)
insertionSort :: Ord a => [a] -> [a] insertionSort = foldr insert []
-- Example use: -- *Main> insertionSort [6,8,5,9,3,2,1,4,7] -- [1,2,3,4,5,6,7,8,9]</lang>
HicEst
<lang hicest>DO i = 2, LEN(A)
value = A(i) j = i - 1 1 IF( j > 0 ) THEN IF( A(j) > value ) THEN A(j+1) = A(j) j = j - 1 GOTO 1 ! no WHILE in HicEst ENDIF ENDIF A(j+1) = value
ENDDO</lang>
Icon and Unicon
<lang Icon>procedure main() #: demonstrate various ways to sort a list and string
demosort(insertionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
procedure insertionsort(X,op) #: return sorted X local i,temp
op := sortop(op,X) # select how and what we sort every i := 2 to *X do { temp := X[j := i] while op(temp,X[1 <= (j -:= 1)]) do X[j+1] := X[j] X[j+1] := temp } return X
end</lang>
Note: This example relies on the supporting procedures 'sortop', and 'demosort' in Bubble Sort. The full demosort exercises the named sort of a list with op = "numeric", "string", ">>" (lexically gt, descending),">" (numerically gt, descending), a custom comparator, and also a string.
Abbreviated sample output:
Sorting Demo using procedure insertionsort on list : [ 3 14 1 5 9 2 6 3 ] with op = &null: [ 1 2 3 3 5 6 9 14 ] (0 ms) ... on string : "qwerty" with op = &null: "eqrtwy" (0 ms)
J
Solution inspired by the Common LISP solution: <lang J>isort=:((>: # ]) , [ , < #])/</lang> Example of use: <lang J> isort 32 4 1 34 95 3 2 120 _38 _38 1 2 3 4 32 34 95 120</lang>
Java
<lang java5>public static void insertSort(int[] A){
for(int i = 1; i < A.length; i++){ int value = A[i]; int j = i - 1; while(j >= 0 && A[j] > value){ A[j + 1] = A[j]; j = j - 1; } A[j + 1] = value; }
}</lang>
JavaScript
<lang javascript> function insertionSort (a) {
for (var i = 0; i < a.length; i++) { for (var j = 0; j < i; j++) { if (a[i] < a[j]) { var k = a.splice(i, 1); a.splice(j, 0, k); break; } } } return a;
}
var a = [4, 65, 2, -31, 0, 99, 83, 782, 1]; insertionSort(a); document.write(a.join(" ")); </lang>
Io
<lang io> List do(
insertionSortInPlace := method( for(j, 1, size - 1, key := at(j) i := j - 1
while(i >= 0 and at(i) > key, atPut(i + 1, at(i)) i = i - 1 ) atPut(i + 1, key) ) )
)
lst := list(7, 6, 5, 9, 8, 4, 3, 1, 2, 0) lst insertionSortInPlace println # ==> list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)</lang>
A shorter, but slightly less efficient, version: <lang io>List do(
insertionSortInPlace := method( # In fact, we could've done slice(1, size - 1) foreach(...) # but creating a new list in memory can only make it worse. foreach(idx, key, newidx := slice(0, idx) map(x, x > key) indexOf(true) if(newidx, insertAt(removeAt(idx), newidx)) ) self)
)
lst := list(7, 6, 5, 9, 8, 4, 3, 1, 2, 0) lst insertionSortInPlace println # ==> list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) </lang>
Lua
<lang lua>function bins(tb, val, st, en)
local st, en = st or 1, en or #tb local mid = math.floor((st + en)/2) if en == st then return tb[st] > val and st or st+1 else return tb[mid] > val and bins(tb, val, st, mid) or bins(tb, val, mid+1, en) end
end function isort(t)
local ret = {t[1], t[2]} for i = 3, #t do table.insert(ret, bins(ret, t[i]), t[i]) end return ret
end
print(unpack(isort{4,5,2,7,8,3}))</lang>
MATLAB
This is a direct translation of the pseudo-code above, except that it has been modified to compensate for MATLAB's 1 based arrays. <lang MATLAB>function list = insertionSort(list)
for i = (2:numel(list)) value = list(i); j = i - 1; while (j >= 1) && (list(j) > value) list(j+1) = list(j); j = j-1; end list(j+1) = value; end %for
end %insertionSort</lang>
Sample Usage: <lang MATLAB>>> insertionSort([4 3 1 5 6 2])
ans =
1 2 3 4 5 6</lang>
Modula-3
<lang modula3>MODULE InsertSort;
PROCEDURE IntSort(VAR item: ARRAY OF INTEGER) =
VAR j, value: INTEGER; BEGIN FOR i := FIRST(item) + 1 TO LAST(item) DO value := item[i]; j := i - 1; WHILE j >= FIRST(item) AND item[j] > value DO item[j + 1] := item[j]; DEC(j); END; item[j + 1] := value; END; END IntSort;
END InsertSort.</lang>
Objeck
<lang objeck> bundle Default {
class Insert { function : Main(args : String[]) ~ Nil { values := [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10]; InsertionSort(values); each(i : values) { values[i]->PrintLine(); }; } function : InsertionSort (a : Int[]) ~ Nil { each(i : a) { value := a[i]; j := i - 1; while(j >= 0 & a[j] > value) { a[j + 1] := a[j]; j -= 1; }; a[j + 1] := value; }; } }
} </lang>
OCaml
<lang ocaml>let rec insert x = function
[] -> [x]
| y :: ys ->
if x <= y then x :: y :: ys else y :: insert x ys
let insertion_sort lst = List.fold_right insert lst [];;
insertion_sort [6;8;5;9;3;2;1;4;7];;</lang>
Oz
Direct translation of pseudocode. In-place sorting of mutable arrays. <lang oz>declare
proc {InsertionSort A} Low = {Array.low A} High = {Array.high A} in for I in Low+1..High do Value = A.I J = {NewCell I-1} in for while:@J >= Low andthen A.@J > Value do A.(@J+1) := A.@J J := @J - 1 end A.(@J+1) := Value end end
Arr = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)}
in
{InsertionSort Arr} {Show {Array.toRecord unit Arr}}</lang>
Perl
<lang perl> sub insertion_sort {
my @a = @_; for my $i (0 .. $#a) { for my $j (0 .. $i - 1) { if ($a[$i] < $a[$j]) { my $k = splice @a, $i, 1; splice @a, $j, 0, $k; last; } } } @a;
}
my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1);
@a = insertion_sort @a;
print "@a\n";
</lang>
Output:
-31 0 1 2 4 65 83 99 782
Perl 6
<lang perl6>sub insertion_sort ( @a is copy ) {
for 1 .. @a.end -> $i { my $value = @a[$i]; my $j; loop ( $j = $i-1; $j >= 0 and @a[$j] > $value; $j-- ) { @a[$j+1] = @a[$j]; } @a[$j+1] = $value; } return @a;
}
my @data = 22, 7, 2, -5, 8, 4; say 'input = ' ~ @data; say 'output = ' ~ @data.&insertion_sort; </lang>
Output:
input = 22 7 2 -5 8 4 output = -5 2 4 7 8 22
PHP
<lang php>function insertionSort(&$arr){ for($i=0;$i<count($arr);$i++){ $val = $arr[$i]; $j = $i-1; while($j>=0 && $arr[$j] > $val){ $arr[$j+1] = $arr[$j]; $j--; } $arr[$j+1] = $val; } }
$arr = array(4,2,1,6,9,3,8,7); insertionSort($arr); echo implode(',',$arr);</lang>
1,2,3,4,6,7,8,9
PicoLisp
<lang PicoLisp>(de insertionSort (Lst)
(for (I (cdr Lst) I (cdr I)) (for (J Lst (n== J I) (cdr J)) (T (> (car J) (car I)) (rot J (offset I J)) ) ) ) Lst )</lang>
Output:
: (insertionSort (5 3 1 7 4 1 1 20)) -> (1 1 1 3 4 5 7 20)
PL/I
<lang pli> INSSORT: PROCEDURE (A);
DCL A(*) FIXED BIN(31); DCL (I, J, V, N) FIXED BIN(31);
N = HBOUND(A,1); M = LBOUND(A,1); DO I=M+1 TO N; V=A(I); J=I-1; DO WHILE (J > M-1); if A(J) <= V then leave; A(J+1)=A(J); J=J-1; END; A(J+1)=V; END; RETURN;
END INSSORT; </lang>
Prolog
<lang prolog>insert_sort(L1,L2) :-
insert_sort_intern(L1,[],L2).
insert_sort_intern([],L,L). insert_sort_intern([H|T],L1,L) :-
insert(L1,H,L2), insert_sort_intern(T,L2,L).
insert([],X,[X]). insert([H|T],X,[X,H|T]) :-
X =< H, !.
insert([H|T],X,[H|T2]) :-
insert(T,X,T2).</lang> % Example use: % ?- insert_sort([2,23,42,3,10,1,34,5],L). % L = [1,2,3,5,10,23,34,42] ? % yes
PureBasic
<lang PureBasic>Procedure insertionSort(Array a(1))
Protected low, high Protected firstIndex, lastIndex = ArraySize(a()) If lastIndex > firstIndex + 1 low = firstIndex + 1 While low <= lastIndex high = low While high > firstIndex If a(high) < a(high - 1) Swap a(high), a(high - 1) Else Break EndIf high - 1 Wend low + 1 Wend EndIf
EndProcedure</lang>
Python
<lang python>def insertion_sort(l):
for i in xrange(1, len(l)): j = i-1 key = l[i] while (l[j] > key) and (j >= 0): l[j+1] = l[j] j -= 1 l[j+1] = key</lang>
Insertion sort with binary search
<lang python>def insertion_sort_bin(seq):
for i in range(1, len(seq)): key = seq[i] # invariant: ``seq[:i]`` is sorted # find the least `low' such that ``seq[low]`` is not less then `key'. # Binary search in sorted sequence ``seq[low:up]``: low, up = 0, i while up > low: middle = (low + up) // 2 if seq[middle] < key: low = middle + 1 else: up = middle # insert key at position ``low`` seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:]</lang>
R
Direct translation of pseudocode. <lang r>insertionsort <- function(x) {
for(i in 2:(length(x))) { value <- x[i] j <- i - 1 while(j >= 1 && x[j] > value) { x[j+1] <- x[j] j <- j-1 } x[j+1] <- value } x
} insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</lang>
REALbasic
<lang vb>Sub InsertionSort(theList() as Integer)
for insertionElementIndex as Integer = 1 to UBound(theList) dim insertionElement as Integer = theList(insertionElementIndex) dim j as Integer = insertionElementIndex - 1 while (j >= 0) and (insertionElement < theList(j)) theList(j + 1) = theList(j) j = j - 1 wend theList(j + 1) = insertionElement next
End Sub</lang>
REXX
<lang rexx>/*REXX program sorts an array using the insertion-sort method. */
call gen@ /*generate array elements. */ call show@ 'before sort' /*show before array elements*/ call insertionSort highItem /*invoke the insertion sort.*/ call show@ ' after sort' /*show after array elements*/ exit
/*─────────────────────────────────────INSERTIONSORT subroutine────*/
insertionSort: procedure expose @.; parse arg highItem
do i=2 to highItem value=@.i
do j=i-1 by -1 while j\==0 & @.j>value jp1=j+1 @.jp1=@.j end
jp1=j+1 @.jp1=value end
return
/*─────────────────────────────────────GEN@ subroutine─────────────*/
gen@: @.= /*assign default value. */
@.1="---Monday's Child Is Fair of Face (by Mother Goose)---" @.2="Monday's child is fair of face;" @.3="Tuesday's child is full of grace;" @.4="Wednesday's child is full of woe;" @.5="Thursday's child has far to go;" @.6="Friday's child is loving and giving;" @.7="Saturday's child works hard for a living;" @.8="But the child that is born on the Sabbath day" @.9="Is blithe and bonny, good and gay."
do highItem=1 while @.highItem\== /*find how many entries. */ end
highItem=highItem-1 /*adjust highItem slightly. */ return
/*─────────────────────────────────────SHOW@ subroutine────────────*/
show@: widthH=length(highItem) /*maximum width of any line.*/
do j=1 for highItem say 'element' right(j,widthH) arg(1)':' @.j end
say copies('─',80) /*show a seperator line. */ return</lang>
Output:
element 1 before sort: ---Monday's Child Is Fair of Face (by Mother Goose)--- element 2 before sort: Monday's child is fair of face; element 3 before sort: Tuesday's child is full of grace; element 4 before sort: Wednesday's child is full of woe; element 5 before sort: Thursday's child has far to go; element 6 before sort: Friday's child is loving and giving; element 7 before sort: Saturday's child works hard for a living; element 8 before sort: But the child that is born on the Sabbath day element 9 before sort: Is blithe and bonny, good and gay. ──────────────────────────────────────────────────────────────────────────────── element 1 after sort: ---Monday's Child Is Fair of Face (by Mother Goose)--- element 2 after sort: But the child that is born on the Sabbath day element 3 after sort: Friday's child is loving and giving; element 4 after sort: Is blithe and bonny, good and gay. element 5 after sort: Monday's child is fair of face; element 6 after sort: Saturday's child works hard for a living; element 7 after sort: Thursday's child has far to go; element 8 after sort: Tuesday's child is full of grace; element 9 after sort: Wednesday's child is full of woe; ────────────────────────────────────────────────────────────────────────────────
Ruby
<lang ruby>class Array
def insertionsort! 1.upto(length - 1) do |i| value = self[i] j = i - 1 while j >= 0 and self[j] > value self[j+1] = self[j] j -= 1 end self[j+1] = value end self end
end ary = [7,6,5,9,8,4,3,1,2,0] ary.insertionsort!
- => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</lang>
Scala
<lang scala>def insert(list: List[Int], value: Int) = list.span(_ < value) match {
case (lower, upper) => lower ::: value :: upper
} def insertSort(list: List[Int]) = list.foldLeft(List[Int]())(insert)</lang>
Scheme
<lang scheme>(define (insert x lst)
(if (null? lst) (list x) (let ((y (car lst)) (ys (cdr lst))) (if (<= x y) (cons x lst) (cons y (insert x ys))))))
(define (insertion-sort lst)
(if (null? lst) '() (insert (car lst) (insertion-sort (cdr lst)))))
(insertion-sort '(6 8 5 9 3 2 1 4 7))</lang>
Seed7
<lang seed7>const proc: insertionSort (inout array elemType: arr) is func
local var integer: i is 0; var integer: j is 0; var elemType: help is elemType.value; begin for i range 2 to length(arr) do j := i; help := arr[i]; while j > 1 and arr[pred(j)] > help do arr[j] := arr[pred(j)]; decr(j); end while; arr[j] := help; end for; end func;</lang>
Original source: [1]
SNOBOL4
<lang snobol>* read data into an array A = table() i = 0 readln A = trim(input) :s(readln) aSize = i - 1
- sort array
i = 1 loop1 value = A j = i - 1 loop2 gt(j,0) gt(A<j>,value) :f(done2) A<j + 1> = A<j> j = j - 1 :(loop2) done2 A<j + 1> = value i = ?lt(i,aSize) i + 1 :s(loop1) i = 1
- output sorted data
while output = A; i = ?lt(i,aSize) i + 1 :s(while) end</lang>
Standard ML
<lang sml>fun insertion_sort cmp = let
fun insert (x, []) = [x] | insert (x, y::ys) = case cmp (x, y) of GREATER => y :: insert (x, ys) | _ => x :: y :: ys
in
foldl insert []
end;
insertion_sort Int.compare [6,8,5,9,3,2,1,4,7];</lang>
TI-83 BASIC
Store input in L1, run prgmSORTINS, get output in L2.
:L1→L2 :0→A :Lbl L :A+1→A :A→B :While B>0 :If L2(B)<L2(B+1) :Goto B :L2(B)→C :L2(B+1)→L2(B) :C→L2(B+1) :B-1→B :End :Lbl B :If A<(dim(L2)-1) :Goto L :DelVar A :DelVar B :DelVar C :Stop
Tcl
<lang tcl>package require Tcl 8.5
proc insertionsort {m} {
for {set i 1} {$i < [llength $m]} {incr i} { set val [lindex $m $i] set j [expr {$i - 1}] while {$j >= 0 && [lindex $m $j] > $val} { lset m [expr {$j + 1}] [lindex $m $j] incr j -1 } lset m [expr {$j + 1}] $val } return $m
}
puts [insertionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</lang>
TI-83 BASIC
Input into L1, run prgmSORTINS, output in L2.
:"INSERTION" :L1→L2 :0→A :Lbl L :A+1→A :A→B :While B>0 :If L2(B)≤L2(B+1) :Goto B :L2(B)→C :L2(B+1)→L2(B) :C→L2(B+1) :B-1→B :End :Lbl B :If A<(dim(L2)-1) :Goto L :DelVar A :DelVar B :DelVar C :Return
UnixPipes
<lang bash>selectionsort() {
read a test -n "$a" && ( selectionsort | sort -nm <(echo $a) -)
}</lang> <lang bash>cat to.sort | selectionsort</lang>
Ursala
<lang Ursala>#import nat
insort = ~&i&& @hNCtX ~&r->lx ^\~&rt nleq-~rlrSPrhlPrSCPTlrShlPNCTPQ@rhPlD</lang> test program: <lang Ursala>#cast %nL
example = insort <45,82,69,82,104,58,88,112,89,74></lang> output:
<45,58,69,74,82,82,88,89,104,112>
Yorick
Based on pseudocode, except using 1-based arrays. <lang yorick>func insertionSort(&A) {
for(i = 2; i <= numberof(A); i++) { value = A(i); j = i - 1; while(j >= 1 && A(j) > value) { A(j+1) = A(j); j--; } A(j+1) = value; }
}</lang>
- Programming Tasks
- Sorting Algorithms
- WikipediaSourced
- ActionScript
- Ada
- ALGOL 68
- AutoHotkey
- AWK
- BASIC
- BBC BASIC
- C
- C++
- C sharp
- Clojure
- COBOL
- Common Lisp
- D
- E
- Examples needing attention
- Eiffel
- Emacs Lisp
- Erlang
- Forth
- Fortran
- GAP
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- J
- Java
- JavaScript
- Io
- Lua
- MATLAB
- Modula-3
- Objeck
- OCaml
- Oz
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- Prolog
- PureBasic
- Python
- R
- REALbasic
- REXX
- Ruby
- Scala
- Scheme
- Seed7
- SNOBOL4
- Standard ML
- TI-83 BASIC
- Tcl
- UnixPipes
- Ursala
- Yorick