Sorting algorithms/Insertion sort: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 34: | Line 34: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F insertion_sort(&l) |
||
L(i) 1 .< l.len |
L(i) 1 .< l.len |
||
V j = i - 1 |
V j = i - 1 |
||
Line 45: | Line 45: | ||
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] |
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] |
||
insertion_sort(&arr) |
insertion_sort(&arr) |
||
print(arr)</ |
print(arr)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 56: | Line 56: | ||
These programs use two ASSIST macros (XDECO, XPRNT) to keep the code as short as possible. |
These programs use two ASSIST macros (XDECO, XPRNT) to keep the code as short as possible. |
||
===Basic=== |
===Basic=== |
||
< |
<syntaxhighlight lang="360asm">* Insertion sort 16/06/2016 |
||
INSSORT CSECT |
INSSORT CSECT |
||
USING INSSORT,R13 base register |
USING INSSORT,R13 base register |
||
Line 112: | Line 112: | ||
XDEC DS CL12 for xdeco |
XDEC DS CL12 for xdeco |
||
YREGS symbolics for registers |
YREGS symbolics for registers |
||
END INSSORT</ |
END INSSORT</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 120: | Line 120: | ||
===Assembler Structured Macros=== |
===Assembler Structured Macros=== |
||
No harmful gotos [:)Dijkstra], no labels. It's cleaner, but is it clearer? |
No harmful gotos [:)Dijkstra], no labels. It's cleaner, but is it clearer? |
||
< |
<syntaxhighlight lang="360asm">* Insertion sort 16/06/2016 |
||
INSSORTS CSECT |
INSSORTS CSECT |
||
USING INSSORTS,R13 base register |
USING INSSORTS,R13 base register |
||
Line 172: | Line 172: | ||
XDEC DS CL12 for xdeco |
XDEC DS CL12 for xdeco |
||
YREGS symbolics for registers |
YREGS symbolics for registers |
||
END INSSORTS</ |
END INSSORTS</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Same as previous |
Same as previous |
||
Line 178: | Line 178: | ||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program insertionSort64.s */ |
/* program insertionSort64.s */ |
||
Line 340: | Line 340: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun insert (x xs) |
||
(cond ((endp xs) (list x)) |
(cond ((endp xs) (list x)) |
||
((< x (first xs)) |
((< x (first xs)) |
||
Line 353: | Line 353: | ||
nil |
nil |
||
(insert (first xs) |
(insert (first xs) |
||
(isort (rest xs)))))</ |
(isort (rest xs)))))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size) |
||
INT i |
INT i |
||
Line 407: | Line 407: | ||
Test(c,8) |
Test(c,8) |
||
Test(d,12) |
Test(d,12) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Insertion_sort.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Insertion_sort.png Screenshot from Atari 8-bit computer] |
||
Line 433: | Line 433: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">function insertionSort(array:Array) |
||
{ |
{ |
||
for(var i:int = 1; i < array.length;i++) |
for(var i:int = 1; i < array.length;i++) |
||
Line 447: | Line 447: | ||
} |
} |
||
return array; |
return array; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">type Data_Array is array(Natural range <>) of Integer; |
||
procedure Insertion_Sort(Item : in out Data_Array) is |
procedure Insertion_Sort(Item : in out Data_Array) is |
||
Line 467: | Line 467: | ||
Item(J + 1) := Value; |
Item(J + 1) := Value; |
||
end loop; |
end loop; |
||
end Insertion_Sort;</ |
end Insertion_Sort;</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 477: | Line 477: | ||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
||
< |
<syntaxhighlight lang="algol68">MODE DATA = REF CHAR; |
||
PROC in place insertion sort = (REF[]DATA item)VOID: |
PROC in place insertion sort = (REF[]DATA item)VOID: |
||
Line 501: | Line 501: | ||
in place insertion sort(ref data); |
in place insertion sort(ref data); |
||
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line); |
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line); |
||
print((data))</ |
print((data))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 510: | Line 510: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
External in-place insertion sort routine for integers. From the pseudo code but with variable bounds. |
External in-place insertion sort routine for integers. From the pseudo code but with variable bounds. |
||
< |
<syntaxhighlight lang="algolw">% insertion sorts in-place the array A. As Algol W procedures can't find the bounds % |
||
% of an array parameter, the lower and upper bounds must be specified in lb and ub % |
% of an array parameter, the lower and upper bounds must be specified in lb and ub % |
||
procedure insertionSortI ( integer array A ( * ); integer value lb, ub ) ; |
procedure insertionSortI ( integer array A ( * ); integer value lb, ub ) ; |
||
Line 522: | Line 522: | ||
end while_j_ge_0_and_Aj_gt_v ; |
end while_j_ge_0_and_Aj_gt_v ; |
||
A( j + 1 ) := v |
A( j + 1 ) := v |
||
end insertionSortI ;</ |
end insertionSortI ;</syntaxhighlight> |
||
Test the insertionSortI procedure. |
Test the insertionSortI procedure. |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% external in-place insertion sort procedure % |
% external in-place insertion sort procedure % |
||
procedure insertionSortI ( integer array A( * ); integer value lb, ub ) ; |
procedure insertionSortI ( integer array A( * ); integer value lb, ub ) ; |
||
Line 539: | Line 539: | ||
write( i_w := 1, d( 1 ) ); |
write( i_w := 1, d( 1 ) ); |
||
for i := 2 until 8 do writeon( i_w := 1, d( i ) ) |
for i := 2 until 8 do writeon( i_w := 1, d( i ) ) |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 547: | Line 547: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">-- In-place insertion sort |
||
on insertionSort(theList, l, r) -- Sort items l thru r of theList. |
on insertionSort(theList, l, r) -- Sort items l thru r of theList. |
||
set listLength to (count theList) |
set listLength to (count theList) |
||
Line 599: | Line 599: | ||
set aList to {60, 73, 11, 66, 6, 77, 41, 97, 59, 45, 64, 15, 91, 100, 22, 89, 77, 59, 54, 61} |
set aList to {60, 73, 11, 66, 6, 77, 41, 97, 59, 45, 64, 15, 91, 100, 22, 89, 77, 59, 54, 61} |
||
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. |
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. |
||
return aList</ |
return aList</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
< |
<syntaxhighlight lang="applescript">{6, 11, 15, 22, 41, 45, 54, 59, 59, 60, 61, 64, 66, 73, 77, 77, 89, 91, 97, 100}</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program insertionSort.s */ |
/* program insertionSort.s */ |
||
Line 830: | Line 830: | ||
bx lr @ leave function |
bx lr @ leave function |
||
iMagicNumber: .int 0xCCCCCCCD |
iMagicNumber: .int 0xCCCCCCCD |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">insertionSort: function [items][ |
||
arr: new items |
arr: new items |
||
loop 1..(size items)-1 'i [ |
loop 1..(size items)-1 'i [ |
||
Line 851: | Line 851: | ||
] |
] |
||
print insertionSort [3 1 2 8 5 7 9 4 6]</ |
print insertionSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 863: | Line 863: | ||
This implementation finds the position at which the element is to be inserted, and then uses '''array_subcirculate''' to move it into place. The prelude's implementation of '''array_subcirculate''' is a '''memmove(3)'''. |
This implementation finds the position at which the element is to be inserted, and then uses '''array_subcirculate''' to move it into place. The prelude's implementation of '''array_subcirculate''' is a '''memmove(3)'''. |
||
< |
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats" |
||
(*------------------------------------------------------------------*) |
(*------------------------------------------------------------------*) |
||
Line 948: | Line 948: | ||
print! (" ", arr[i]); |
print! (" ", arr[i]); |
||
println! () |
println! () |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 962: | Line 962: | ||
(The complications are necessary to prevent us accidentally having two copies of a linear value. Having two copies would introduce such nasty possibilities as a double-free error, use of a destroyed list, etc.) |
(The complications are necessary to prevent us accidentally having two copies of a linear value. Having two copies would introduce such nasty possibilities as a double-free error, use of a destroyed list, etc.) |
||
< |
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats" |
||
(*------------------------------------------------------------------*) |
(*------------------------------------------------------------------*) |
||
Line 1,123: | Line 1,123: | ||
array_uninitize<Strptr1> (arr, i2sz SIZE); |
array_uninitize<Strptr1> (arr, i2sz SIZE); |
||
array_ptr_free (pf_arr, pfgc_arr | p_arr) |
array_ptr_free (pf_arr, pfgc_arr | p_arr) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,137: | Line 1,137: | ||
None of the activities in the following implementation requires allocating a new node. The original list is consumed. However, you can use this code to non-destructively sort a non-linear list by first creating a copy, casting the copy to a linear list, and sorting the copy, then casting the result to a non-linear list. |
None of the activities in the following implementation requires allocating a new node. The original list is consumed. However, you can use this code to non-destructively sort a non-linear list by first creating a copy, casting the copy to a linear list, and sorting the copy, then casting the result to a non-linear list. |
||
< |
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats" |
||
(*------------------------------------------------------------------*) |
(*------------------------------------------------------------------*) |
||
Line 1,322: | Line 1,322: | ||
val () = list_vt_freelin lst |
val () = list_vt_freelin lst |
||
in |
in |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,332: | Line 1,332: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276481.html#276481 forum] |
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276481.html#276481 forum] |
||
< |
<syntaxhighlight lang="autohotkey">MsgBox % InsertionSort("") |
||
MsgBox % InsertionSort("xxx") |
MsgBox % InsertionSort("xxx") |
||
MsgBox % InsertionSort("3,2,1") |
MsgBox % InsertionSort("3,2,1") |
||
Line 1,348: | Line 1,348: | ||
sorted .= "," . a%A_Index% |
sorted .= "," . a%A_Index% |
||
Return SubStr(sorted,2) ; drop leading comma |
Return SubStr(sorted,2) ; drop leading comma |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Sort standard input (storing lines into an array) and output to standard output |
Sort standard input (storing lines into an array) and output to standard output |
||
< |
<syntaxhighlight lang="awk">{ |
||
line[NR] = $0 |
line[NR] = $0 |
||
} |
} |
||
Line 1,369: | Line 1,369: | ||
print line[i] |
print line[i] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Bash}}== |
=={{header|Bash}}== |
||
< |
<syntaxhighlight lang="bash">#!/bin/bash |
||
# Sorting integers with insertion sort |
# Sorting integers with insertion sort |
||
Line 1,452: | Line 1,452: | ||
fi |
fi |
||
#END</ |
#END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,465: | Line 1,465: | ||
=={{header|B4X}}== |
=={{header|B4X}}== |
||
The array type can be changed to Object and it will then work with any numeric type. |
The array type can be changed to Object and it will then work with any numeric type. |
||
< |
<syntaxhighlight lang="b4x">Sub InsertionSort (A() As Int) |
||
For i = 1 To A.Length - 1 |
For i = 1 To A.Length - 1 |
||
Dim value As Int = A(i) |
Dim value As Int = A(i) |
||
Line 1,484: | Line 1,484: | ||
Next |
Next |
||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,500: | Line 1,500: | ||
This version should work on any BASIC that can accept arrays as function arguments. |
This version should work on any BASIC that can accept arrays as function arguments. |
||
< |
<syntaxhighlight lang="qbasic">DECLARE SUB InsertionSort (theList() AS INTEGER) |
||
DIM n(10) AS INTEGER, L AS INTEGER, o AS STRING |
DIM n(10) AS INTEGER, L AS INTEGER, o AS STRING |
||
Line 1,529: | Line 1,529: | ||
theList(j + 1) = insertionElement |
theList(j + 1) = insertionElement |
||
NEXT |
NEXT |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,540: | Line 1,540: | ||
Sorts N elements in array i() into ascending order. Invoke with GO SUB 500. |
Sorts N elements in array i() into ascending order. Invoke with GO SUB 500. |
||
< |
<syntaxhighlight lang="zxbasic">500 FOR j=1 TO N-1 |
||
510 IF i(j)<=i(j+1) THEN NEXT j: RETURN |
510 IF i(j)<=i(j+1) THEN NEXT j: RETURN |
||
520 LET c=i(j+1) |
520 LET c=i(j+1) |
||
530 FOR k=j TO 1 STEP -1: IF i(k)>c THEN LET i(k+1)=i(k): NEXT k |
530 FOR k=j TO 1 STEP -1: IF i(k)>c THEN LET i(k+1)=i(k): NEXT k |
||
540 LET i(k+1)=c |
540 LET i(k+1)=c |
||
600 NEXT j: RETURN</ |
600 NEXT j: RETURN</syntaxhighlight> |
||
For those who prefer GO TOs over conditional NEXTs (fine in ZX BASIC but problematic for compilers and stack-dependent interpreters like NextBASIC’s integer extensions) replace NEXT J: RETURN in line 510 with GO TO 600 and use this line 530: |
For those who prefer GO TOs over conditional NEXTs (fine in ZX BASIC but problematic for compilers and stack-dependent interpreters like NextBASIC’s integer extensions) replace NEXT J: RETURN in line 510 with GO TO 600 and use this line 530: |
||
Line 1,554: | Line 1,554: | ||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
Note that the array index is assumed to start at zero. |
Note that the array index is assumed to start at zero. |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM test(9) |
||
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 |
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 |
||
PROCinsertionsort(test(), 10) |
PROCinsertionsort(test(), 10) |
||
Line 1,574: | Line 1,574: | ||
a(j%) = t |
a(j%) = t |
||
NEXT |
NEXT |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,581: | Line 1,581: | ||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
< |
<syntaxhighlight lang="basic"> |
||
10 DIM A(10): N=9 |
10 DIM A(10): N=9 |
||
11 REM GENERATE SOME RANDOM NUMBERS AND PRINT THEM |
11 REM GENERATE SOME RANDOM NUMBERS AND PRINT THEM |
||
Line 1,590: | Line 1,590: | ||
32 RETURN |
32 RETURN |
||
50 PRINT: FOR I=0 TO N: PRINTA(I): NEXT: RETURN |
50 PRINT: FOR I=0 TO N: PRINTA(I): NEXT: RETURN |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic"> 100 PROGRAM "InserSrt.bas" |
||
110 RANDOMIZE |
110 RANDOMIZE |
||
120 NUMERIC ARRAY(5 TO 21) |
120 NUMERIC ARRAY(5 TO 21) |
||
Line 1,619: | Line 1,619: | ||
340 LET A(I+1)=SW |
340 LET A(I+1)=SW |
||
350 NEXT |
350 NEXT |
||
360 END DEF</ |
360 END DEF</syntaxhighlight> |
||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">get "libhdr" |
||
let insertionSort(A, len) be |
let insertionSort(A, len) be |
||
Line 1,647: | Line 1,647: | ||
insertionSort(array, length) |
insertionSort(array, length) |
||
write("After: ", array, length) |
write("After: ", array, length) |
||
$)</ |
$)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Before: 4 65 2 -31 0 99 2 83 782 1 |
<pre>Before: 4 65 2 -31 0 99 2 83 782 1 |
||
Line 1,653: | Line 1,653: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
void insertion_sort(int*, const size_t); |
void insertion_sort(int*, const size_t); |
||
Line 1,685: | Line 1,685: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,693: | Line 1,693: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">namespace Sort { |
||
using System; |
using System; |
||
Line 1,713: | Line 1,713: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang="csharp"> using Sort; |
||
using System; |
using System; |
||
Line 1,724: | Line 1,724: | ||
Console.WriteLine(String.Join(" ", entries)); |
Console.WriteLine(String.Join(" ", entries)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 1,730: | Line 1,730: | ||
g++ -std=c++11 insertion.cpp |
g++ -std=c++11 insertion.cpp |
||
Uses binary search via std::upper_bound() to find the insertion position in logarithmic time and then performs the insertion via std::rotate() in linear time. |
Uses binary search via std::upper_bound() to find the insertion position in logarithmic time and then performs the insertion via std::rotate() in linear time. |
||
< |
<syntaxhighlight lang="cpp">#include <algorithm> |
||
#include <iostream> |
#include <iostream> |
||
#include <iterator> |
#include <iterator> |
||
Line 1,762: | Line 1,762: | ||
std::cout << "\n"; |
std::cout << "\n"; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,769: | Line 1,769: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure"> |
||
(defn insertion-sort [coll] |
(defn insertion-sort [coll] |
||
(reduce (fn [result input] |
(reduce (fn [result input] |
||
Line 1,776: | Line 1,776: | ||
[] |
[] |
||
coll)) |
coll)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Translated from the Haskell example: |
Translated from the Haskell example: |
||
< |
<syntaxhighlight lang="clojure"> |
||
(defn in-sort! [data] |
(defn in-sort! [data] |
||
(letfn [(insert ([raw x](insert [] raw x)) |
(letfn [(insert ([raw x](insert [] raw x)) |
||
Line 1,788: | Line 1,788: | ||
(reduce insert [] data))) |
(reduce insert [] data))) |
||
;Usage:(in-sort! [6,8,5,9,3,2,1,4,7]) |
;Usage:(in-sort! [6,8,5,9,3,2,1,4,7]) |
||
;Returns: [1 2 3 4 5 6 7 8 9]</ |
;Returns: [1 2 3 4 5 6 7 8 9]</syntaxhighlight> |
||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">% Insertion-sort an array in place. |
||
insertion_sort = proc [T: type] (a: array[T]) |
insertion_sort = proc [T: type] (a: array[T]) |
||
where T has lt: proctype (T,T) returns (bool) |
where T has lt: proctype (T,T) returns (bool) |
||
Line 1,826: | Line 1,826: | ||
insertion_sort[int](test) |
insertion_sort[int](test) |
||
stream$puts(po, "After: ") print_arr[int](test, 3, po) |
stream$puts(po, "After: ") print_arr[int](test, 3, po) |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Before: 7 -5 0 2 99 16 4 20 47 19 |
<pre>Before: 7 -5 0 2 99 16 4 20 47 19 |
||
Line 1,832: | Line 1,832: | ||
=={{header|CMake}}== |
=={{header|CMake}}== |
||
< |
<syntaxhighlight lang="cmake"># insertion_sort(var [value1 value2...]) sorts a list of integers. |
||
function(insertion_sort var) |
function(insertion_sort var) |
||
math(EXPR last "${ARGC} - 1") # Sort ARGV[1..last]. |
math(EXPR last "${ARGC} - 1") # Sort ARGV[1..last]. |
||
Line 1,862: | Line 1,862: | ||
endforeach(i) |
endforeach(i) |
||
set("${var}" "${answer}" PARENT_SCOPE) |
set("${var}" "${answer}" PARENT_SCOPE) |
||
endfunction(insertion_sort)</ |
endfunction(insertion_sort)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="cmake">insertion_sort(result 33 11 44 22 66 55) |
||
message(STATUS "${result}") # -- 11;22;33;44;55;66</ |
message(STATUS "${result}") # -- 11;22;33;44;55;66</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|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. |
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. |
||
< |
<syntaxhighlight lang="cobol"> C-PROCESS SECTION. |
||
PERFORM E-INSERTION VARYING WB-IX-1 FROM 1 BY 1 |
PERFORM E-INSERTION VARYING WB-IX-1 FROM 1 BY 1 |
||
UNTIL WB-IX-1 > WC-SIZE. |
UNTIL WB-IX-1 > WC-SIZE. |
||
Line 1,895: | Line 1,895: | ||
F-999. |
F-999. |
||
EXIT.</ |
EXIT.</syntaxhighlight> |
||
And a fully runnable version, by Steve Williams |
And a fully runnable version, by Steve Williams |
||
{{works with|GnuCOBOL}} |
{{works with|GnuCOBOL}} |
||
<syntaxhighlight lang="cobol"> |
|||
<lang COBOL> |
|||
>>SOURCE FORMAT FREE |
>>SOURCE FORMAT FREE |
||
*> This code is dedicated to the public domain |
*> This code is dedicated to the public domain |
||
Line 1,969: | Line 1,969: | ||
stop run |
stop run |
||
. |
. |
||
end program insertionsort.</ |
end program insertionsort.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,978: | Line 1,978: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun span (predicate list) |
||
(let ((tail (member-if-not predicate list))) |
(let ((tail (member-if-not predicate list))) |
||
(values (ldiff list tail) tail))) |
(values (ldiff list tail) tail))) |
||
Line 1,990: | Line 1,990: | ||
(defun insertion-sort (list) |
(defun insertion-sort (list) |
||
(reduce #'insert list :initial-value nil))</ |
(reduce #'insert list :initial-value nil))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(defun insertion-sort (sequence &optional (predicate #'<)) |
||
(if (cdr sequence) |
(if (cdr sequence) |
||
(insert (car sequence) ;; insert the current item into |
(insert (car sequence) ;; insert the current item into |
||
Line 2,009: | Line 2,009: | ||
(insert item ;; the list of the item sorted with the rest of the list |
(insert item ;; the list of the item sorted with the rest of the list |
||
(cdr sequence) |
(cdr sequence) |
||
predicate)))))</ |
predicate)))))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void insertionSort(T)(T[] data) pure nothrow @safe @nogc { |
||
foreach (immutable i, value; data[1 .. $]) { |
foreach (immutable i, value; data[1 .. $]) { |
||
auto j = i + 1; |
auto j = i + 1; |
||
Line 2,026: | Line 2,026: | ||
items.insertionSort; |
items.insertionSort; |
||
items.writeln; |
items.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre> |
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre> |
||
Line 2,032: | Line 2,032: | ||
===Higher Level Version=== |
===Higher Level Version=== |
||
{{trans|C++}} |
{{trans|C++}} |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.range, std.algorithm, std.traits; |
||
void insertionSort(R)(R arr) |
void insertionSort(R)(R arr) |
||
Line 2,062: | Line 2,062: | ||
assert(arr3.isSorted); |
assert(arr3.isSorted); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>arr1 sorted: [2, 4, 11, 17, 19, 24, 25, 28, 44, 46] |
<pre>arr1 sorted: [2, 4, 11, 17, 19, 24, 25, 28, 44, 46] |
||
Line 2,071: | Line 2,071: | ||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="dart"> |
||
insertSort(List<int> array){ |
insertSort(List<int> array){ |
||
Line 2,090: | Line 2,090: | ||
print('${a}'); |
print('${a}'); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>array unsorted: [10, 3, 11, 15, 19, 1]; |
<pre>array unsorted: [10, 3, 11, 15, 19, 1]; |
||
Line 2,101: | Line 2,101: | ||
Static array is an arbitrary-based array of fixed length |
Static array is an arbitrary-based array of fixed length |
||
< |
<syntaxhighlight lang="delphi">program TestInsertionSort; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 2,150: | Line 2,150: | ||
Writeln; |
Writeln; |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,159: | Line 2,159: | ||
===String sort=== |
===String sort=== |
||
// string is 1-based variable-length array of Char |
// string is 1-based variable-length array of Char |
||
< |
<syntaxhighlight lang="delphi">procedure InsertionSort(var S: string); |
||
var |
var |
||
I, J, L: Integer; |
I, J, L: Integer; |
||
Line 2,175: | Line 2,175: | ||
S[J + 1]:= Ch; |
S[J + 1]:= Ch; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
<pre> |
<pre> |
||
// in : S = 'the quick brown fox jumps over the lazy dog' |
// in : S = 'the quick brown fox jumps over the lazy dog' |
||
Line 2,185: | Line 2,185: | ||
A direct conversion of the pseudocode. |
A direct conversion of the pseudocode. |
||
< |
<syntaxhighlight lang="e">def insertionSort(array) { |
||
for i in 1..!(array.size()) { |
for i in 1..!(array.size()) { |
||
def value := array[i] |
def value := array[i] |
||
Line 2,195: | Line 2,195: | ||
array[j+1] := value |
array[j+1] := value |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Test case: |
Test case: |
||
< |
<syntaxhighlight 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) |
> insertionSort(a) |
||
> 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()</ |
# 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()</syntaxhighlight> |
||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
<lang>subr sort |
<syntaxhighlight lang="text">subr sort |
||
for i = 1 to len data[] - 1 |
for i = 1 to len data[] - 1 |
||
h = data[i] |
h = data[i] |
||
Line 2,219: | Line 2,219: | ||
data[] = [ 29 4 72 44 55 26 27 77 92 5 ] |
data[] = [ 29 4 72 44 55 26 27 77 92 5 ] |
||
call sort |
call sort |
||
print data[]</ |
print data[]</syntaxhighlight> |
||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
Line 2,228: | Line 2,228: | ||
For a more complete explanation of the Eiffel sort examples, see the [[Sorting algorithms/Bubble sort#Eiffel|Bubble sort]]. |
For a more complete explanation of the Eiffel sort examples, see the [[Sorting algorithms/Bubble sort#Eiffel|Bubble sort]]. |
||
< |
<syntaxhighlight lang="eiffel">class |
||
MY_SORTED_SET [G -> COMPARABLE] |
MY_SORTED_SET [G -> COMPARABLE] |
||
inherit |
inherit |
||
Line 2,259: | Line 2,259: | ||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0 : |
ELENA 5.0 : |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
extension op |
extension op |
||
Line 2,295: | Line 2,295: | ||
console.printLine("before:", list.asEnumerable()); |
console.printLine("before:", list.asEnumerable()); |
||
console.printLine("after :", list.insertionSort().asEnumerable()); |
console.printLine("after :", list.insertionSort().asEnumerable()); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,303: | Line 2,303: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Sort do |
||
def insert_sort(list) when is_list(list), do: insert_sort(list, []) |
def insert_sort(list) when is_list(list), do: insert_sort(list, []) |
||
Line 2,312: | Line 2,312: | ||
defp insert(x, sorted) when x < hd(sorted), do: [x | sorted] |
defp insert(x, sorted) when x < hd(sorted), do: [x | sorted] |
||
defp insert(x, [h | t]), do: [h | insert(x, t)] |
defp insert(x, [h | t]), do: [h | insert(x, t)] |
||
end</ |
end</syntaxhighlight> |
||
Example: |
Example: |
||
Line 2,321: | Line 2,321: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun min-or-max-of-a-list (numbers comparator) |
||
"Return minimum or maximum of NUMBERS using COMPARATOR." |
"Return minimum or maximum of NUMBERS using COMPARATOR." |
||
(let ((extremum (car numbers))) |
(let ((extremum (car numbers))) |
||
Line 2,350: | Line 2,350: | ||
nil)) |
nil)) |
||
(insertion-sort '(1 2 3 9 8 7 25 12 3 2 1) #'>)</ |
(insertion-sort '(1 2 3 9 8 7 25 12 3 2 1) #'>)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,357: | Line 2,357: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">-module(sort). |
||
-export([insertion/1]). |
-export([insertion/1]). |
||
Line 2,364: | Line 2,364: | ||
insert(X,[]) -> [X]; |
insert(X,[]) -> [X]; |
||
insert(X,L=[H|_]) when X =< H -> [X|L]; |
insert(X,L=[H|_]) when X =< H -> [X|L]; |
||
insert(X,[H|T]) -> [H|insert(X, T)].</ |
insert(X,[H|T]) -> [H|insert(X, T)].</syntaxhighlight> |
||
And the calls: |
And the calls: |
||
< |
<syntaxhighlight lang="erlang">1> c(sort). |
||
{ok,sort} |
{ok,sort} |
||
2> sort:insertion([5,3,9,4,1,6,8,2,7]). |
2> sort:insertion([5,3,9,4,1,6,8,2,7]). |
||
[1,2,3,4,5,6,7,8,9]</ |
[1,2,3,4,5,6,7,8,9]</syntaxhighlight> |
||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
Note: array index is assumed to start at zero. |
Note: array index is assumed to start at zero. |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM INSERTION_SORT |
PROGRAM INSERTION_SORT |
||
Line 2,408: | Line 2,408: | ||
PRINT |
PRINT |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,416: | Line 2,416: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">function insertion_sort(sequence s) |
||
object temp |
object temp |
||
integer j |
integer j |
||
Line 2,437: | Line 2,437: | ||
pretty_print(1,s,{2}) |
pretty_print(1,s,{2}) |
||
puts(1,"\nAfter: ") |
puts(1,"\nAfter: ") |
||
pretty_print(1,insertion_sort(s),{2})</ |
pretty_print(1,insertion_sort(s),{2})</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,475: | Line 2,475: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
Procedural Version |
Procedural Version |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// This function performs an insertion sort with an array. |
// This function performs an insertion sort with an array. |
||
// The input parameter is a generic array (any type that can perform comparison). |
// The input parameter is a generic array (any type that can perform comparison). |
||
Line 2,490: | Line 2,490: | ||
B.[j+1] <- value |
B.[j+1] <- value |
||
B // the array B is returned |
B // the array B is returned |
||
</syntaxhighlight> |
|||
</lang> |
|||
Functional Version |
Functional Version |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let insertionSort collection = |
let insertionSort collection = |
||
Line 2,509: | Line 2,509: | ||
| x::xs, ys -> xs |> isort (sinsert x ys) |
| x::xs, ys -> xs |> isort (sinsert x ys) |
||
collection |> isort [] |
collection |> isort [] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
< |
<syntaxhighlight lang="factor">USING: kernel prettyprint sorting.extras sequences ; |
||
: insertion-sort ( seq -- sorted-seq ) |
: insertion-sort ( seq -- sorted-seq ) |
||
<reversed> V{ } clone [ swap insort-left! ] reduce ; |
<reversed> V{ } clone [ swap insort-left! ] reduce ; |
||
{ 6 8 5 9 3 2 1 4 7 } insertion-sort .</ |
{ 6 8 5 9 3 2 1 4 7 } insertion-sort .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,527: | Line 2,527: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: insert ( start end -- start ) |
||
dup @ >r ( r: v ) \ v = a[i] |
dup @ >r ( r: v ) \ v = a[i] |
||
begin |
begin |
||
Line 2,544: | Line 2,544: | ||
create test 7 , 3 , 0 , 2 , 9 , 1 , 6 , 8 , 4 , 5 , |
create test 7 , 3 , 0 , 2 , 9 , 1 , 6 , 8 , 4 , 5 , |
||
test 10 sort |
test 10 sort |
||
test 10 cells dump</ |
test 10 cells dump</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">subroutine sort(n, a) |
||
implicit none |
implicit none |
||
integer :: n, i, j |
integer :: n, i, j |
||
Line 2,564: | Line 2,564: | ||
a(j + 1) = x |
a(j + 1) = x |
||
end do |
end do |
||
end subroutine</ |
end subroutine</syntaxhighlight> |
||
=== Alternate Fortran 77 version === |
=== Alternate Fortran 77 version === |
||
< |
<syntaxhighlight lang="fortran"> SUBROUTINE SORT(N,A) |
||
IMPLICIT NONE |
IMPLICIT NONE |
||
INTEGER N,I,J |
INTEGER N,I,J |
||
Line 2,581: | Line 2,581: | ||
20 A(J + 1) = X |
20 A(J + 1) = X |
||
30 CONTINUE |
30 CONTINUE |
||
END</ |
END</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' version 20-10-2016 |
||
' compile with: fbc -s console |
' compile with: fbc -s console |
||
' for boundry checks on array's compile with: fbc -s console -exx |
' for boundry checks on array's compile with: fbc -s console -exx |
||
Line 2,633: | Line 2,633: | ||
Print : Print "hit any key to end program" |
Print : Print "hit any key to end program" |
||
Sleep |
Sleep |
||
End</ |
End</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>unsort -7 -1 4 -6 5 2 1 -2 0 -5 -4 6 -3 7 3 |
<pre>unsort -7 -1 4 -6 5 2 1 -2 0 -5 -4 6 -3 7 3 |
||
Line 2,639: | Line 2,639: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">InsertionSort := function(L) |
||
local n, i, j, x; |
local n, i, j, x; |
||
n := Length(L); |
n := Length(L); |
||
Line 2,656: | Line 2,656: | ||
InsertionSort(s); |
InsertionSort(s); |
||
s; |
s; |
||
# "ABCDEFGHIJKLMNOPQRSTUVWXYZ"</ |
# "ABCDEFGHIJKLMNOPQRSTUVWXYZ"</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 2,681: | Line 2,681: | ||
insertionSort(list) |
insertionSort(list) |
||
fmt.Println("sorted! ", list) |
fmt.Println("sorted! ", list) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,689: | Line 2,689: | ||
A generic version that takes any container that conforms to <code>sort.Interface</code>: |
A generic version that takes any container that conforms to <code>sort.Interface</code>: |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,710: | Line 2,710: | ||
insertionSort(sort.IntSlice(list)) |
insertionSort(sort.IntSlice(list)) |
||
fmt.Println("sorted! ", list) |
fmt.Println("sorted! ", list) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,718: | Line 2,718: | ||
Using binary search to locate the place to insert: |
Using binary search to locate the place to insert: |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 2,740: | Line 2,740: | ||
insertionSort(list) |
insertionSort(list) |
||
fmt.Println("sorted! ", list) |
fmt.Println("sorted! ", list) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,749: | Line 2,749: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def insertionSort = { list -> |
||
def size = list.size() |
def size = list.size() |
||
Line 2,761: | Line 2,761: | ||
} |
} |
||
list |
list |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight 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]))</ |
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]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,772: | Line 2,772: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Data.List (insert) |
||
insertionSort :: Ord a => [a] -> [a] |
insertionSort :: Ord a => [a] -> [a] |
||
Line 2,779: | Line 2,779: | ||
-- Example use: |
-- Example use: |
||
-- *Main> insertionSort [6,8,5,9,3,2,1,4,7] |
-- *Main> insertionSort [6,8,5,9,3,2,1,4,7] |
||
-- [1,2,3,4,5,6,7,8,9]</ |
-- [1,2,3,4,5,6,7,8,9]</syntaxhighlight> |
||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
< |
<syntaxhighlight lang="haxe">class InsertionSort { |
||
@:generic |
@:generic |
||
public static function sort<T>(arr:Array<T>) { |
public static function sort<T>(arr:Array<T>) { |
||
Line 2,814: | Line 2,814: | ||
Sys.println('Sorted Strings: ' + stringArray); |
Sys.println('Sorted Strings: ' + stringArray); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,827: | Line 2,827: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">DO i = 2, LEN(A) |
||
value = A(i) |
value = A(i) |
||
j = i - 1 |
j = i - 1 |
||
Line 2,838: | Line 2,838: | ||
ENDIF |
ENDIF |
||
A(j+1) = value |
A(j+1) = value |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main() #: demonstrate various ways to sort a list and string |
||
demosort(insertionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") |
demosort(insertionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") |
||
end |
end |
||
Line 2,857: | Line 2,857: | ||
} |
} |
||
return X |
return X |
||
end</ |
end</syntaxhighlight> |
||
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| 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. |
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| 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. |
||
Line 2,871: | Line 2,871: | ||
=={{header|Io}}== |
=={{header|Io}}== |
||
<syntaxhighlight lang="io"> |
|||
<lang io> |
|||
List do( |
List do( |
||
insertionSortInPlace := method( |
insertionSortInPlace := method( |
||
Line 2,888: | Line 2,888: | ||
lst := list(7, 6, 5, 9, 8, 4, 3, 1, 2, 0) |
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)</ |
lst insertionSortInPlace println # ==> list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)</syntaxhighlight> |
||
A shorter, but slightly less efficient, version: |
A shorter, but slightly less efficient, version: |
||
< |
<syntaxhighlight lang="io">List do( |
||
insertionSortInPlace := method( |
insertionSortInPlace := method( |
||
# In fact, we could've done slice(1, size - 1) foreach(...) |
# In fact, we could've done slice(1, size - 1) foreach(...) |
||
Line 2,904: | Line 2,904: | ||
lst := list(7, 6, 5, 9, 8, 4, 3, 1, 2, 0) |
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) |
lst insertionSortInPlace println # ==> list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Isabelle}}== |
=={{header|Isabelle}}== |
||
< |
<syntaxhighlight lang="isabelle">theory Insertionsort |
||
imports Main |
imports Main |
||
begin |
begin |
||
Line 2,964: | Line 2,964: | ||
unfolding rosettacode_haskell_insertionsort_def by(induction xs) simp+ |
unfolding rosettacode_haskell_insertionsort_def by(induction xs) simp+ |
||
end</ |
end</syntaxhighlight> |
||
Line 2,970: | Line 2,970: | ||
{{eff note|J|/:~}} |
{{eff note|J|/:~}} |
||
Solution inspired by the Common LISP solution: |
Solution inspired by the Common LISP solution: |
||
< |
<syntaxhighlight lang="j">isort=:((>: # ]) , [ , < #])/</syntaxhighlight> |
||
Example of use: |
Example of use: |
||
< |
<syntaxhighlight lang="j"> isort 32 4 1 34 95 3 2 120 _38 |
||
_38 1 2 3 4 32 34 95 120</ |
_38 1 2 3 4 32 34 95 120</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java5">public static void insertSort(int[] A){ |
||
for(int i = 1; i < A.length; i++){ |
for(int i = 1; i < A.length; i++){ |
||
int value = A[i]; |
int value = A[i]; |
||
Line 2,986: | Line 2,986: | ||
A[j + 1] = value; |
A[j + 1] = value; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Using some built-in algorithms (warning: not stable, due to the lack of an "upper bound" binary search function) |
Using some built-in algorithms (warning: not stable, due to the lack of an "upper bound" binary search function) |
||
{{trans|C++}} |
{{trans|C++}} |
||
< |
<syntaxhighlight lang="java5">public static <E extends Comparable<? super E>> void insertionSort(List<E> a) { |
||
for (int i = 1; i < a.size(); i++) { |
for (int i = 1; i < a.size(); i++) { |
||
int j = Math.abs(Collections.binarySearch(a.subList(0, i), a.get(i)) + 1); |
int j = Math.abs(Collections.binarySearch(a.subList(0, i), a.get(i)) + 1); |
||
Line 3,003: | Line 3,003: | ||
a[j] = x; |
a[j] = x; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript"> |
||
function insertionSort (a) { |
function insertionSort (a) { |
||
for (var i = 0; i < a.length; i++) { |
for (var i = 0; i < a.length; i++) { |
||
Line 3,019: | Line 3,019: | ||
var a = [4, 65, 2, -31, 0, 99, 83, 782, 1]; |
var a = [4, 65, 2, -31, 0, 99, 83, 782, 1]; |
||
insertionSort(a); |
insertionSort(a); |
||
document.write(a.join(" "));</ |
document.write(a.join(" "));</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
{{works with|jq|1.4}} |
{{works with|jq|1.4}} |
||
The insertion sort can be expressed directly in jq as follows: |
The insertion sort can be expressed directly in jq as follows: |
||
< |
<syntaxhighlight lang="jq">def insertion_sort: |
||
reduce .[] as $x ([]; insert($x));</ |
reduce .[] as $x ([]; insert($x));</syntaxhighlight>where insert/1 inserts its argument into its input, which can, by construction, be assumed here to be sorted. This algorithm will work in jq for any JSON array. |
||
The following solution uses an "industrial strength" implementation of bsearch (binary search) that requires the following control structure: |
The following solution uses an "industrial strength" implementation of bsearch (binary search) that requires the following control structure: |
||
< |
<syntaxhighlight lang="jq"># As soon as "condition" is true, then emit . and stop: |
||
def do_until(condition; next): |
def do_until(condition; next): |
||
def u: if condition then . else (next|u) end; |
def u: if condition then . else (next|u) end; |
||
u;</ |
u;</syntaxhighlight> |
||
bsearch is the only non-trivial part of this solution, and so we include |
bsearch is the only non-trivial part of this solution, and so we include |
||
Line 3,040: | Line 3,040: | ||
(-1 - ix), where ix is the insertion point that would leave the array sorted. |
(-1 - ix), where ix is the insertion point that would leave the array sorted. |
||
If the input is not sorted, bsearch will terminate but with irrelevant results.< |
If the input is not sorted, bsearch will terminate but with irrelevant results.<syntaxhighlight lang="jq">def bsearch(target): |
||
if length == 0 then -1 |
if length == 0 then -1 |
||
elif length == 1 then |
elif length == 1 then |
||
Line 3,077: | Line 3,077: | ||
def insertion_sort: |
def insertion_sort: |
||
reduce .[] as $x ([]; insert($x));</ |
reduce .[] as $x ([]; insert($x));</syntaxhighlight> |
||
Example:< |
Example:<syntaxhighlight lang="jq">[1, 2, 1, 1.1, -1.1, null, [null], {"null":null}] | insertion_sort</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
[null,-1.1,1,1,1.1,2,[null],{"null":null}] |
[null,-1.1,1,1,1.1,2,[null],{"null":null}] |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia"># v0.6 |
||
function insertionsort!(A::Array{T}) where T <: Number |
function insertionsort!(A::Array{T}) where T <: Number |
||
Line 3,099: | Line 3,099: | ||
x = randn(5) |
x = randn(5) |
||
@show x insertionsort!(x)</ |
@show x insertionsort!(x)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,106: | Line 3,106: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="kotlin">fun insertionSort(array: IntArray) { |
||
for (index in 1 until array.size) { |
for (index in 1 until array.size) { |
||
val value = array[index] |
val value = array[index] |
||
Line 3,132: | Line 3,132: | ||
insertionSort(numbers) |
insertionSort(numbers) |
||
printArray("Sorted:", numbers) |
printArray("Sorted:", numbers) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,139: | Line 3,139: | ||
=={{header|Ksh}}== |
=={{header|Ksh}}== |
||
< |
<syntaxhighlight lang="ksh">#!/bin/ksh |
||
# An insertion sort in ksh |
# An insertion sort in ksh |
||
Line 3,177: | Line 3,177: | ||
printf "%d " ${arr[i]} |
printf "%d " ${arr[i]} |
||
done |
done |
||
printf "%s\n" " )"</ |
printf "%s\n" " )"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,183: | Line 3,183: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
{def sort |
{def sort |
||
Line 3,209: | Line 3,209: | ||
{sort {A}} |
{sort {A}} |
||
-> [-31,0,1,2,4,65,83,99,782] |
-> [-31,0,1,2,4,65,83,99,782] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb"> itemCount = 20 |
||
dim A(itemCount) |
dim A(itemCount) |
||
for i = 1 to itemCount |
for i = 1 to itemCount |
||
Line 3,242: | Line 3,242: | ||
next i |
next i |
||
print |
print |
||
return</ |
return</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Binary variation of Insertion sort (Has better complexity) |
Binary variation of Insertion sort (Has better complexity) |
||
< |
<syntaxhighlight lang="lua">do |
||
local function lower_bound(container, container_begin, container_end, value, comparator) |
local function lower_bound(container, container_begin, container_end, value, comparator) |
||
local count = container_end - container_begin + 1 |
local count = container_end - container_begin + 1 |
||
Line 3,291: | Line 3,291: | ||
binary_insertion_sort_impl(container, comparator) |
binary_insertion_sort_impl(container, comparator) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lua">function bins(tb, val, st, en) |
||
local st, en = st or 1, en or #tb |
local st, en = st or 1, en or #tb |
||
local mid = math.floor((st + en)/2) |
local mid = math.floor((st + en)/2) |
||
Line 3,308: | Line 3,308: | ||
end |
end |
||
print(unpack(isort{4,5,2,7,8,3}))</ |
print(unpack(isort{4,5,2,7,8,3}))</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">arr := Array([17,3,72,0,36,2,3,8,40,0]): |
||
len := numelems(arr): |
len := numelems(arr): |
||
for i from 2 to len do |
for i from 2 to len do |
||
Line 3,322: | Line 3,322: | ||
arr[j+1] := val: |
arr[j+1] := val: |
||
end do: |
end do: |
||
arr;</ |
arr;</syntaxhighlight> |
||
{{Out|Output}} |
{{Out|Output}} |
||
<pre>[0,0,2,3,3,8,17,36,40,72]</pre> |
<pre>[0,0,2,3,3,8,17,36,40,72]</pre> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">insertionSort[a_List] := Module[{A = a}, |
||
For[i = 2, i <= Length[A], i++, |
For[i = 2, i <= Length[A], i++, |
||
value = A[[i]]; j = i - 1; |
value = A[[i]]; j = i - 1; |
||
Line 3,333: | Line 3,333: | ||
A[[j + 1]] = value;]; |
A[[j + 1]] = value;]; |
||
A |
A |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>insertionSort@{ 2, 1, 3, 5} |
<pre>insertionSort@{ 2, 1, 3, 5} |
||
Line 3,340: | Line 3,340: | ||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
This is a direct translation of the pseudo-code above, except that it has been modified to compensate for MATLAB's 1 based arrays. |
This is a direct translation of the pseudo-code above, except that it has been modified to compensate for MATLAB's 1 based arrays. |
||
< |
<syntaxhighlight lang="matlab">function list = insertionSort(list) |
||
for i = (2:numel(list)) |
for i = (2:numel(list)) |
||
Line 3,355: | Line 3,355: | ||
end %for |
end %for |
||
end %insertionSort</ |
end %insertionSort</syntaxhighlight> |
||
Sample Usage: |
Sample Usage: |
||
< |
<syntaxhighlight lang="matlab">>> insertionSort([4 3 1 5 6 2]) |
||
ans = |
ans = |
||
1 2 3 4 5 6</ |
1 2 3 4 5 6</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">insertion_sort(u) := block( |
||
[n: length(u), x, j], |
[n: length(u), x, j], |
||
for i from 2 thru n do ( |
for i from 2 thru n do ( |
||
Line 3,376: | Line 3,376: | ||
u[j + 1]: x |
u[j + 1]: x |
||
) |
) |
||
)$</ |
)$</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
<syntaxhighlight lang="maxscript"> |
|||
<lang MAXScript> |
|||
fn inSort arr = |
fn inSort arr = |
||
( |
( |
||
Line 3,394: | Line 3,394: | ||
return arr |
return arr |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<syntaxhighlight lang="maxscript"> |
|||
<lang MAXScript> |
|||
b = for i in 1 to 20 collect random 1 40 |
b = for i in 1 to 20 collect random 1 40 |
||
#(2, 28, 35, 31, 27, 24, 2, 22, 15, 34, 9, 10, 22, 40, 26, 5, 23, 6, 18, 33) |
#(2, 28, 35, 31, 27, 24, 2, 22, 15, 34, 9, 10, 22, 40, 26, 5, 23, 6, 18, 33) |
||
a = insort b |
a = insort b |
||
#(2, 2, 5, 6, 9, 10, 15, 18, 22, 22, 23, 24, 26, 27, 28, 31, 33, 34, 35, 40) |
#(2, 2, 5, 6, 9, 10, 15, 18, 22, 22, 23, 24, 26, 27, 28, 31, 33, 34, 35, 40) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ML}}== |
=={{header|ML}}== |
||
==={{header|mLite}}=== |
==={{header|mLite}}=== |
||
{{trans|OCaml}} |
{{trans|OCaml}} |
||
< |
<syntaxhighlight lang="ocaml">fun insertion_sort L = |
||
let |
let |
||
fun insert |
fun insert |
||
Line 3,420: | Line 3,420: | ||
println ` insertion_sort [6,8,5,9,3,2,1,4,7]; |
println ` insertion_sort [6,8,5,9,3,2,1,4,7]; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output |
Output |
||
<pre> |
<pre> |
||
Line 3,427: | Line 3,427: | ||
==={{header|Standard ML}}=== |
==={{header|Standard ML}}=== |
||
< |
<syntaxhighlight lang="sml">fun insertion_sort cmp = let |
||
fun insert (x, []) = [x] |
fun insert (x, []) = [x] |
||
| insert (x, y::ys) = |
| insert (x, y::ys) = |
||
Line 3,436: | Line 3,436: | ||
end; |
end; |
||
insertion_sort Int.compare [6,8,5,9,3,2,1,4,7];</ |
insertion_sort Int.compare [6,8,5,9,3,2,1,4,7];</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
{{trans|Ada}} |
{{trans|Ada}} |
||
< |
<syntaxhighlight lang="modula3">MODULE InsertSort; |
||
PROCEDURE IntSort(VAR item: ARRAY OF INTEGER) = |
PROCEDURE IntSort(VAR item: ARRAY OF INTEGER) = |
||
Line 3,455: | Line 3,455: | ||
END; |
END; |
||
END IntSort; |
END IntSort; |
||
END InsertSort.</ |
END InsertSort.</syntaxhighlight> |
||
=={{header|N/t/roff}}== |
=={{header|N/t/roff}}== |
||
Line 3,462: | Line 3,462: | ||
===Sliding method=== |
===Sliding method=== |
||
< |
<syntaxhighlight lang="n/t/roff">.de end |
||
.. |
.. |
||
.de array |
.de array |
||
Line 3,516: | Line 3,516: | ||
.a.pushln 13 64 22 87 54 87 23 92 11 64 5 9 3 3 0 |
.a.pushln 13 64 22 87 54 87 23 92 11 64 5 9 3 3 0 |
||
.insertionsort a |
.insertionsort a |
||
.a.dump</ |
.a.dump</syntaxhighlight> |
||
===Swapping method=== |
===Swapping method=== |
||
< |
<syntaxhighlight lang="n/t/roff">.de end |
||
.. |
.. |
||
.de array |
.de array |
||
Line 3,563: | Line 3,563: | ||
.a.pushln 13 64 22 87 54 87 23 92 11 64 5 9 3 3 0 |
.a.pushln 13 64 22 87 54 87 23 92 11 64 5 9 3 3 0 |
||
.insertionsort a |
.insertionsort a |
||
.a.dump</ |
.a.dump</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nanoquery">def insertion_sort(L) |
||
for i in range(1, len(L) - 1) |
for i in range(1, len(L) - 1) |
||
j = i - 1 |
j = i - 1 |
||
Line 3,579: | Line 3,579: | ||
return L |
return L |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
From the psuedocode. |
From the psuedocode. |
||
< |
<syntaxhighlight lang="nemerle">using System.Console; |
||
using Nemerle.English; |
using Nemerle.English; |
||
Line 3,609: | Line 3,609: | ||
foreach (i in arr) Write($"$i "); |
foreach (i in arr) Write($"$i "); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols binary |
options replace format comments java crossref savelog symbols binary |
||
Line 3,659: | Line 3,659: | ||
return ArrayList(A) |
return ArrayList(A) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,682: | Line 3,682: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc insertSort[T](a: var openarray[T]) = |
||
for i in 1 .. a.high: |
for i in 1 .. a.high: |
||
let value = a[i] |
let value = a[i] |
||
Line 3,693: | Line 3,693: | ||
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] |
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] |
||
insertSort a |
insertSort a |
||
echo a</ |
echo a</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre> |
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class Insert { |
class Insert { |
||
Line 3,722: | Line 3,722: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let rec insert lst x = |
||
match lst with |
match lst with |
||
[] -> [x] |
[] -> [x] |
||
Line 3,734: | Line 3,734: | ||
let insertion_sort = List.fold_left insert [];; |
let insertion_sort = List.fold_left insert [];; |
||
insertion_sort [6;8;5;9;3;2;1;4;7];;</ |
insertion_sort [6;8;5;9;3;2;1;4;7];;</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 3,740: | Line 3,740: | ||
Returns a new sorted list. |
Returns a new sorted list. |
||
< |
<syntaxhighlight lang="oforth">: insertionSort(a) |
||
| l i j v | |
| l i j v | |
||
a asListBuffer ->l |
a asListBuffer ->l |
||
Line 3,753: | Line 3,753: | ||
l put(j 1 +, v) |
l put(j 1 +, v) |
||
] |
] |
||
l ;</ |
l ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,764: | Line 3,764: | ||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
{{trans|REXX}} |
{{trans|REXX}} |
||
< |
<syntaxhighlight lang="oorexx">/* REXX program sorts a stemmed array (has characters) */ |
||
/* using the insertion sort algorithm */ |
/* using the insertion sort algorithm */ |
||
Call gen /* fill the array with test data */ |
Call gen /* fill the array with test data */ |
||
Line 3,806: | Line 3,806: | ||
Say 'Element' right(j,length(x.0)) arg(1)":" x.j |
Say 'Element' right(j,length(x.0)) arg(1)":" x.j |
||
End |
End |
||
Return</ |
Return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Element 1 before sort: ---Monday's Child Is Fair of Face (by Mother Goose)--- |
<pre>Element 1 before sort: ---Monday's Child Is Fair of Face (by Mother Goose)--- |
||
Line 3,832: | Line 3,832: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
Direct translation of pseudocode. In-place sorting of mutable arrays. |
Direct translation of pseudocode. In-place sorting of mutable arrays. |
||
< |
<syntaxhighlight lang="oz">declare |
||
proc {InsertionSort A} |
proc {InsertionSort A} |
||
Low = {Array.low A} |
Low = {Array.low A} |
||
Line 3,852: | Line 3,852: | ||
in |
in |
||
{InsertionSort Arr} |
{InsertionSort Arr} |
||
{Show {Array.toRecord unit Arr}}</ |
{Show {Array.toRecord unit Arr}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">insertionSort(v)={ |
||
for(i=1,#v-1, |
for(i=1,#v-1, |
||
my(j=i-1,x=v[i]); |
my(j=i-1,x=v[i]); |
||
Line 3,865: | Line 3,865: | ||
); |
); |
||
v |
v |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Line 3,871: | Line 3,871: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl"> |
||
sub insertion_sort { |
sub insertion_sort { |
||
my (@list) = @_; |
my (@list) = @_; |
||
Line 3,888: | Line 3,888: | ||
my @a = insertion_sort(4, 65, 2, -31, 0, 99, 83, 782, 1); |
my @a = insertion_sort(4, 65, 2, -31, 0, 99, 83, 782, 1); |
||
print "@a\n"; |
print "@a\n"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
-31 0 1 2 4 65 83 99 782 |
-31 0 1 2 4 65 83 99 782 |
||
Line 3,894: | Line 3,894: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Copy of [[Sorting_algorithms/Insertion_sort#Euphoria|Euphoria]] |
Copy of [[Sorting_algorithms/Insertion_sort#Euphoria|Euphoria]] |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">insertion_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">insertion_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #004080;">object</span> <span style="color: #000000;">temp</span> |
<span style="color: #004080;">object</span> <span style="color: #000000;">temp</span> |
||
Line 3,914: | Line 3,914: | ||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Before: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span> |
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Before: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span> |
||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"After: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">insertion_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"After: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">insertion_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,922: | Line 3,922: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function insertionSort(&$arr){ |
||
for($i=0;$i<count($arr);$i++){ |
for($i=0;$i<count($arr);$i++){ |
||
$val = $arr[$i]; |
$val = $arr[$i]; |
||
Line 3,936: | Line 3,936: | ||
$arr = array(4,2,1,6,9,3,8,7); |
$arr = array(4,2,1,6,9,3,8,7); |
||
insertionSort($arr); |
insertionSort($arr); |
||
echo implode(',',$arr);</ |
echo implode(',',$arr);</syntaxhighlight> |
||
<pre>1,2,3,4,6,7,8,9</pre> |
<pre>1,2,3,4,6,7,8,9</pre> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de insertionSort (Lst) |
||
(for (I (cdr Lst) I (cdr I)) |
(for (I (cdr Lst) I (cdr I)) |
||
(for (J Lst (n== J I) (cdr J)) |
(for (J Lst (n== J I) (cdr J)) |
||
(T (> (car J) (car I)) |
(T (> (car J) (car I)) |
||
(rot J (offset I J)) ) ) ) |
(rot J (offset I J)) ) ) ) |
||
Lst )</ |
Lst )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>: (insertionSort (5 3 1 7 4 1 1 20)) |
<pre>: (insertionSort (5 3 1 7 4 1 1 20)) |
||
Line 3,951: | Line 3,951: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli"> |
||
insert_sort: proc(array); |
insert_sort: proc(array); |
||
dcl array(*) fixed bin(31); |
dcl array(*) fixed bin(31); |
||
Line 3,969: | Line 3,969: | ||
end; |
end; |
||
end insert_sort; |
end insert_sort; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PL/M}}== |
=={{header|PL/M}}== |
||
< |
<syntaxhighlight lang="plm">100H: |
||
/* INSERTION SORT ON 16-BIT INTEGERS */ |
/* INSERTION SORT ON 16-BIT INTEGERS */ |
||
Line 4,017: | Line 4,017: | ||
CALL BDOS(0,0); |
CALL BDOS(0,0); |
||
EOF</ |
EOF</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0 1 2 2 3 4 8 31 65 99 782</pre> |
<pre>0 1 2 2 3 4 8 31 65 99 782</pre> |
||
Line 4,023: | Line 4,023: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
Very similar to the PHP code. |
Very similar to the PHP code. |
||
< |
<syntaxhighlight lang="powershell">function insertionSort($arr){ |
||
for($i=0;$i -lt $arr.length;$i++){ |
for($i=0;$i -lt $arr.length;$i++){ |
||
$val = $arr[$i] |
$val = $arr[$i] |
||
Line 4,037: | Line 4,037: | ||
$arr = @(4,2,1,6,9,3,8,7) |
$arr = @(4,2,1,6,9,3,8,7) |
||
insertionSort($arr) |
insertionSort($arr) |
||
$arr -join ","</ |
$arr -join ","</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1,2,3,4,6,7,8,9</pre> |
<pre>1,2,3,4,6,7,8,9</pre> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog">insert_sort(L1,L2) :- |
||
insert_sort_intern(L1,[],L2). |
insert_sort_intern(L1,[],L2). |
||
Line 4,055: | Line 4,055: | ||
!. |
!. |
||
insert([H|T],X,[H|T2]) :- |
insert([H|T],X,[H|T2]) :- |
||
insert(T,X,T2).</ |
insert(T,X,T2).</syntaxhighlight> |
||
% Example use: |
% Example use: |
||
Line 4,065: | Line 4,065: | ||
Works with SWI-Prolog.<br> |
Works with SWI-Prolog.<br> |
||
Insertion sort inserts elements of a list in a sorted list. So we can use foldl to sort a list. |
Insertion sort inserts elements of a list in a sorted list. So we can use foldl to sort a list. |
||
< |
<syntaxhighlight lang="prolog">% insertion sort |
||
isort(L, LS) :- |
isort(L, LS) :- |
||
foldl(insert, [], L, LS). |
foldl(insert, [], L, LS). |
||
Line 4,084: | Line 4,084: | ||
insert([H | T], N, [H|L1]) :- |
insert([H | T], N, [H|L1]) :- |
||
insert(T, N, L1). |
insert(T, N, L1). |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example use: |
Example use: |
||
<pre> ?- isort([2,23,42,3,10,1,34,5],L). |
<pre> ?- isort([2,23,42,3,10,1,34,5],L). |
||
Line 4,091: | Line 4,091: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure insertionSort(Array a(1)) |
||
Protected low, high |
Protected low, high |
||
Protected firstIndex, lastIndex = ArraySize(a()) |
Protected firstIndex, lastIndex = ArraySize(a()) |
||
Line 4,110: | Line 4,110: | ||
Wend |
Wend |
||
EndIf |
EndIf |
||
EndProcedure</ |
EndProcedure</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def insertion_sort(L): |
||
for i in xrange(1, len(L)): |
for i in xrange(1, len(L)): |
||
j = i-1 |
j = i-1 |
||
Line 4,120: | Line 4,120: | ||
L[j+1] = L[j] |
L[j+1] = L[j] |
||
j -= 1 |
j -= 1 |
||
L[j+1] = key</ |
L[j+1] = key</syntaxhighlight> |
||
Using pythonic iterators: |
Using pythonic iterators: |
||
< |
<syntaxhighlight lang="python">def insertion_sort(L): |
||
for i, value in enumerate(L): |
for i, value in enumerate(L): |
||
for j in range(i - 1, -1, -1): |
for j in range(i - 1, -1, -1): |
||
if L[j] > value: |
if L[j] > value: |
||
L[j + 1] = L[j] |
L[j + 1] = L[j] |
||
L[j] = value</ |
L[j] = value</syntaxhighlight> |
||
===Insertion sort with binary search=== |
===Insertion sort with binary search=== |
||
< |
<syntaxhighlight lang="python">def insertion_sort_bin(seq): |
||
for i in range(1, len(seq)): |
for i in range(1, len(seq)): |
||
key = seq[i] |
key = seq[i] |
||
Line 4,145: | Line 4,145: | ||
up = middle |
up = middle |
||
# insert key at position ``low`` |
# insert key at position ``low`` |
||
seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:]</ |
seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:]</syntaxhighlight> |
||
This is also built-in to the standard library: |
This is also built-in to the standard library: |
||
< |
<syntaxhighlight lang="python">import bisect |
||
def insertion_sort_bin(seq): |
def insertion_sort_bin(seq): |
||
for i in range(1, len(seq)): |
for i in range(1, len(seq)): |
||
bisect.insort(seq, seq.pop(i), 0, i)</ |
bisect.insort(seq, seq.pop(i), 0, i)</syntaxhighlight> |
||
=={{header|Qi}}== |
=={{header|Qi}}== |
||
Based on the scheme version. |
Based on the scheme version. |
||
< |
<syntaxhighlight lang="qi">(define insert |
||
X [] -> [X] |
X [] -> [X] |
||
X [Y|Ys] -> [X Y|Ys] where (<= X Y) |
X [Y|Ys] -> [X Y|Ys] where (<= X Y) |
||
Line 4,166: | Line 4,166: | ||
(insertion-sort [6 8 5 9 3 2 1 4 7]) |
(insertion-sort [6 8 5 9 3 2 1 4 7]) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{Header|Quackery}}== |
=={{Header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery">[ [] swap witheach |
||
[ swap 2dup findwith |
[ swap 2dup findwith |
||
[ over > ] [ ] |
[ over > ] [ ] |
||
nip stuff ] ] is insertionsort ( [ --> [ )</ |
nip stuff ] ] is insertionsort ( [ --> [ )</syntaxhighlight> |
||
=={{header|R}}== |
=={{header|R}}== |
||
Direct translation of pseudocode. |
Direct translation of pseudocode. |
||
< |
<syntaxhighlight lang="r">insertionsort <- function(x) |
||
{ |
{ |
||
for(i in 2:(length(x))) |
for(i in 2:(length(x))) |
||
Line 4,191: | Line 4,191: | ||
x |
x |
||
} |
} |
||
insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</ |
insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</syntaxhighlight> |
||
R has native vectorized operations which allow the following, more efficient implementation. |
R has native vectorized operations which allow the following, more efficient implementation. |
||
<syntaxhighlight lang="r"> |
|||
<lang r> |
|||
insertion_sort <- function(x) { |
insertion_sort <- function(x) { |
||
for (j in 2:length(x)) { |
for (j in 2:length(x)) { |
||
Line 4,213: | Line 4,213: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
This implementation makes use of the pattern matching facilities in the Racket distribution. |
This implementation makes use of the pattern matching facilities in the Racket distribution. |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 4,227: | Line 4,227: | ||
[(cons y rst) (cond [(< x y) (cons x ys)] |
[(cons y rst) (cond [(< x y) (cons x ys)] |
||
[else (cons y (insert x rst))])])) |
[else (cons y (insert x rst))])])) |
||
(foldl insert '() l))</ |
(foldl insert '() l))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>sub insertion_sort ( @a is copy ) { |
||
for 1 .. @a.end -> $i { |
for 1 .. @a.end -> $i { |
||
my $value = @a[$i]; |
my $value = @a[$i]; |
||
Line 4,246: | Line 4,246: | ||
say 'input = ' ~ @data; |
say 'input = ' ~ @data; |
||
say 'output = ' ~ @data.&insertion_sort; |
say 'output = ' ~ @data.&insertion_sort; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 4,254: | Line 4,254: | ||
=={{header|Rascal}}== |
=={{header|Rascal}}== |
||
< |
<syntaxhighlight lang="rascal">import List; |
||
public list[int] insertionSort(a){ |
public list[int] insertionSort(a){ |
||
Line 4,267: | Line 4,267: | ||
} |
} |
||
return a; |
return a; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="rascal">rascal>rascal>insertionSort([4, 65, 2, -31, 0, 99, 83, 782, 1]) |
||
list[int]: [-31,0,1,2,4,65,83,99,782]</ |
list[int]: [-31,0,1,2,4,65,83,99,782]</syntaxhighlight> |
||
=={{header|REALbasic}}== |
=={{header|REALbasic}}== |
||
< |
<syntaxhighlight lang="vb">Sub InsertionSort(theList() as Integer) |
||
for insertionElementIndex as Integer = 1 to UBound(theList) |
for insertionElementIndex as Integer = 1 to UBound(theList) |
||
dim insertionElement as Integer = theList(insertionElementIndex) |
dim insertionElement as Integer = theList(insertionElementIndex) |
||
Line 4,283: | Line 4,283: | ||
theList(j + 1) = insertionElement |
theList(j + 1) = insertionElement |
||
next |
next |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol"> |
||
; This program works with REBOL version R2 and R3, to make it work with Red |
; This program works with REBOL version R2 and R3, to make it work with Red |
||
; change the word func to function |
; change the word func to function |
||
Line 4,326: | Line 4,326: | ||
; just by adding the date! type to the local variable value the same function can sort dates. |
; just by adding the date! type to the local variable value the same function can sort dates. |
||
probe insertion-sort [12-Jan-2015 11-Jan-2015 11-Jan-2016 12-Jan-2014] |
probe insertion-sort [12-Jan-2015 11-Jan-2015 11-Jan-2016 12-Jan-2014] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 4,345: | Line 4,345: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sorts a stemmed array (has characters) using the insertion sort algorithm*/ |
||
call gen /*generate the array's (data) elements.*/ |
call gen /*generate the array's (data) elements.*/ |
||
call show 'before sort' /*display the before array elements. */ |
call show 'before sort' /*display the before array elements. */ |
||
Line 4,374: | Line 4,374: | ||
return |
return |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)": " @.j; end; return</ |
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)": " @.j; end; return</syntaxhighlight> |
||
{{out|output|text= when using the default internal data:}} |
{{out|output|text= when using the default internal data:}} |
||
<pre> |
<pre> |
||
Line 4,401: | Line 4,401: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
alist = [7,6,5,9,8,4,3,1,2,0] |
alist = [7,6,5,9,8,4,3,1,2,0] |
||
see insertionsort(alist) |
see insertionsort(alist) |
||
Line 4,416: | Line 4,416: | ||
next |
next |
||
return blist |
return blist |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">class Array |
||
def insertionsort! |
def insertionsort! |
||
1.upto(length - 1) do |i| |
1.upto(length - 1) do |i| |
||
Line 4,435: | Line 4,435: | ||
ary = [7,6,5,9,8,4,3,1,2,0] |
ary = [7,6,5,9,8,4,3,1,2,0] |
||
p ary.insertionsort! |
p ary.insertionsort! |
||
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</ |
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</syntaxhighlight> |
||
Alternative version which doesn't swap elements but rather removes and inserts the value at the correct place: |
Alternative version which doesn't swap elements but rather removes and inserts the value at the correct place: |
||
< |
<syntaxhighlight lang="ruby">class Array |
||
def insertionsort! |
def insertionsort! |
||
1.upto(length - 1) do |i| |
1.upto(length - 1) do |i| |
||
Line 4,452: | Line 4,452: | ||
ary = [7,6,5,9,8,4,3,1,2,0] |
ary = [7,6,5,9,8,4,3,1,2,0] |
||
p ary.insertionsort! |
p ary.insertionsort! |
||
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</ |
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">dim insSort(100) |
||
sortEnd = 0 |
sortEnd = 0 |
||
global inSort |
global inSort |
||
Line 4,485: | Line 4,485: | ||
insSort(i) = x |
insSort(i) = x |
||
sortEnd = sortEnd + 1 |
sortEnd = sortEnd + 1 |
||
end function</ |
end function</syntaxhighlight> |
||
<pre>End Sort:20 |
<pre>End Sort:20 |
||
1 124 |
1 124 |
||
Line 4,503: | Line 4,503: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn insertion_sort<T: std::cmp::Ord>(arr: &mut [T]) { |
||
for i in 1..arr.len() { |
for i in 1..arr.len() { |
||
let mut j = i; |
let mut j = i; |
||
Line 4,511: | Line 4,511: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|SASL}}== |
=={{header|SASL}}== |
||
Copied from SASL manual, Appendix II, answer (2)(a) |
Copied from SASL manual, Appendix II, answer (2)(a) |
||
<syntaxhighlight lang="sasl">DEF |
|||
<lang SASL>DEF |
|||
sort () = () |
sort () = () |
||
sort (a : x) = insert a (sort x) |
sort (a : x) = insert a (sort x) |
||
Line 4,521: | Line 4,521: | ||
insert a (b : x) = a < b -> a : b : x |
insert a (b : x) = a < b -> a : b : x |
||
b : insert a x |
b : insert a x |
||
?</ |
?</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def insertSort[X](list: List[X])(implicit ord: Ordering[X]) = { |
||
def insert(list: List[X], value: X) = list.span(x => ord.lt(x, value)) match { |
def insert(list: List[X], value: X) = list.span(x => ord.lt(x, value)) match { |
||
case (lower, upper) => lower ::: value :: upper |
case (lower, upper) => lower ::: value :: upper |
||
} |
} |
||
list.foldLeft(List.empty[X])(insert) |
list.foldLeft(List.empty[X])(insert) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (insert x lst) |
||
(if (null? lst) |
(if (null? lst) |
||
(list x) |
(list x) |
||
Line 4,547: | Line 4,547: | ||
(insertion-sort (cdr lst))))) |
(insertion-sort (cdr lst))))) |
||
(insertion-sort '(6 8 5 9 3 2 1 4 7))</ |
(insertion-sort '(6 8 5 9 3 2 1 4 7))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">const proc: insertionSort (inout array elemType: arr) is func |
||
local |
local |
||
var integer: i is 0; |
var integer: i is 0; |
||
Line 4,565: | Line 4,565: | ||
arr[j] := help; |
arr[j] := help; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#insertionSort] |
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#insertionSort] |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">class Array { |
||
method insertion_sort { |
method insertion_sort { |
||
{ |i| |
{ |i| |
||
Line 4,586: | Line 4,586: | ||
var a = 10.of { 100.irand } |
var a = 10.of { 100.irand } |
||
say a.insertion_sort</ |
say a.insertion_sort</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol">* read data into an array |
||
A = table() |
A = table() |
||
i = 0 |
i = 0 |
||
Line 4,608: | Line 4,608: | ||
* output sorted data |
* output sorted data |
||
while output = A<i>; i = ?lt(i,aSize) i + 1 :s(while) |
while output = A<i>; i = ?lt(i,aSize) i + 1 :s(while) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">mata |
||
void insertion_sort(real vector a) { |
void insertion_sort(real vector a) { |
||
real scalar i, j, n, x |
real scalar i, j, n, x |
||
Line 4,625: | Line 4,625: | ||
} |
} |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
Using generics. |
Using generics. |
||
< |
<syntaxhighlight lang="swift">func insertionSort<T:Comparable>(inout list:[T]) { |
||
for i in 1..<list.count { |
for i in 1..<list.count { |
||
var j = i |
var j = i |
||
Line 4,638: | Line 4,638: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc insertionsort {m} { |
proc insertionsort {m} { |
||
Line 4,656: | Line 4,656: | ||
} |
} |
||
puts [insertionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</ |
puts [insertionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</syntaxhighlight> |
||
=={{header|TI-83 BASIC}}== |
=={{header|TI-83 BASIC}}== |
||
Line 4,683: | Line 4,683: | ||
=={{header|uBasic/4tH}}== |
=={{header|uBasic/4tH}}== |
||
<lang>PRINT "Insertion sort:" |
<syntaxhighlight lang="text">PRINT "Insertion sort:" |
||
n = FUNC (_InitArray) |
n = FUNC (_InitArray) |
||
PROC _ShowArray (n) |
PROC _ShowArray (n) |
||
Line 4,731: | Line 4,731: | ||
PRINT |
PRINT |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
< |
<syntaxhighlight lang="bash">selectionsort() { |
||
read a |
read a |
||
test -n "$a" && ( selectionsort | sort -nm <(echo $a) -) |
test -n "$a" && ( selectionsort | sort -nm <(echo $a) -) |
||
}</ |
}</syntaxhighlight> |
||
<lang |
<syntaxhighlight lang="bash">cat to.sort | selectionsort</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
< |
<syntaxhighlight lang="ursala">#import nat |
||
insort = ~&i&& @hNCtX ~&r->lx ^\~&rt nleq-~rlrSPrhlPrSCPTlrShlPNCTPQ@rhPlD</ |
insort = ~&i&& @hNCtX ~&r->lx ^\~&rt nleq-~rlrSPrhlPrSCPTlrShlPNCTPQ@rhPlD</syntaxhighlight> |
||
test program: |
test program: |
||
< |
<syntaxhighlight lang="ursala">#cast %nL |
||
example = insort <45,82,69,82,104,58,88,112,89,74></ |
example = insort <45,82,69,82,104,58,88,112,89,74></syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,755: | Line 4,755: | ||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
{{trans|Nim}} |
{{trans|Nim}} |
||
< |
<syntaxhighlight lang="vala">void insertion_sort(int[] array) { |
||
var count = 0; |
var count = 0; |
||
for (int i = 1; i < array.length; i++) { |
for (int i = 1; i < array.length; i++) { |
||
Line 4,773: | Line 4,773: | ||
foreach (int i in array) |
foreach (int i in array) |
||
print("%d ", i); |
print("%d ", i); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,780: | Line 4,780: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{trans|Phix}}< |
{{trans|Phix}}<syntaxhighlight lang="vb">Option Base 1 |
||
Private Function insertion_sort(s As Variant) As Variant |
Private Function insertion_sort(s As Variant) As Variant |
||
Dim temp As Variant |
Dim temp As Variant |
||
Line 4,801: | Line 4,801: | ||
Debug.Print "Before: ", Join(s, ", ") |
Debug.Print "Before: ", Join(s, ", ") |
||
Debug.Print "After: ", Join(insertion_sort(s), "' ") |
Debug.Print "After: ", Join(insertion_sort(s), "' ") |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>Before: 4, 15, delta, 2, -31, 0, alpha, 19, gamma, 2, 13, beta, 782, 1 |
<pre>Before: 4, 15, delta, 2, -31, 0, alpha, 19, gamma, 2, 13, beta, 782, 1 |
||
After: -31' 0' 1' 2' 2' 4' 13' 15' 19' 782' alpha' beta' delta' gamma</pre> |
After: -31' 0' 1' 2' 2' 4' 13' 15' 19' 782' alpha' beta' delta' gamma</pre> |
||
Line 4,807: | Line 4,807: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
{{trans|REALbasic}} |
{{trans|REALbasic}} |
||
< |
<syntaxhighlight lang="vb">Randomize |
||
Dim n(9) 'nine is the upperbound. |
Dim n(9) 'nine is the upperbound. |
||
'since VBS arrays are 0-based, it will have 10 elements. |
'since VBS arrays are 0-based, it will have 10 elements. |
||
Line 4,843: | Line 4,843: | ||
Next |
Next |
||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>ORIGINAL : 26699;2643;10249;31612;21346;19702;29799;31115;20413;5197; |
<pre>ORIGINAL : 26699;2643;10249;31612;21346;19702;29799;31115;20413;5197; |
||
Line 4,849: | Line 4,849: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang="vlang">fn insertion(mut arr []int) { |
||
for i in 1 .. arr.len { |
for i in 1 .. arr.len { |
||
value := arr[i] |
value := arr[i] |
||
Line 4,866: | Line 4,866: | ||
insertion(mut arr) |
insertion(mut arr) |
||
println('Output: ' + arr.str()) |
println('Output: ' + arr.str()) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Input: [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] |
<pre>Input: [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] |
||
Line 4,872: | Line 4,872: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">var insertionSort = Fn.new { |a| |
||
for (i in 1..a.count-1) { |
for (i in 1..a.count-1) { |
||
var v = a[i] |
var v = a[i] |
||
Line 4,890: | Line 4,890: | ||
System.print("After : %(a)") |
System.print("After : %(a)") |
||
System.print() |
System.print() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,903: | Line 4,903: | ||
Alternatively we can just call a library method. |
Alternatively we can just call a library method. |
||
{{libheader|Wren-sort}} |
{{libheader|Wren-sort}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/sort" for Sort |
||
var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ] |
var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ] |
||
Line 4,911: | Line 4,911: | ||
System.print("After : %(a)") |
System.print("After : %(a)") |
||
System.print() |
System.print() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,919: | Line 4,919: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code ChOut=8, IntOut=11; |
||
proc InsertionSort(A, L); \Sort array A of length L |
proc InsertionSort(A, L); \Sort array A of length L |
||
Line 4,939: | Line 4,939: | ||
InsertionSort(A, 10); |
InsertionSort(A, 10); |
||
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; |
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,949: | Line 4,949: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="yabasic"> |
||
sub InsertionSort (matriz()) |
sub InsertionSort (matriz()) |
||
for i = 1 to arraysize(matriz(),1) |
for i = 1 to arraysize(matriz(),1) |
||
Line 4,979: | Line 4,979: | ||
print |
print |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
Based on pseudocode, except using 1-based arrays. |
Based on pseudocode, except using 1-based arrays. |
||
< |
<syntaxhighlight lang="yorick">func insertionSort(&A) { |
||
for(i = 2; i <= numberof(A); i++) { |
for(i = 2; i <= numberof(A); i++) { |
||
value = A(i); |
value = A(i); |
||
Line 4,994: | Line 4,994: | ||
A(j+1) = value; |
A(j+1) = value; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn insertionSort(list){ |
||
sink:=List(); |
sink:=List(); |
||
foreach x in (list){ |
foreach x in (list){ |
||
Line 5,004: | Line 5,004: | ||
} |
} |
||
sink.close(); |
sink.close(); |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">insertionSort(T(4,65,2,-31,0,99,2,83,782,1)).println(); |
||
insertionSort("big fjords vex quick waltz nymph".split()).println();</ |
insertionSort("big fjords vex quick waltz nymph".split()).println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |