Anonymous user
Sorting algorithms/Insertion sort: Difference between revisions
Sorting algorithms/Insertion sort (view source)
Revision as of 21:57, 29 January 2009
, 15 years agoLinks, formatting, more code -> lang changes
(→{{header|C}}: fixed broken tags for code highlighting) |
m (Links, formatting, more code -> lang changes) |
||
Line 1:
[[Category:Less Than 20 Examples]]{{task|Sorting Algorithms}}
{{Sorting Algorithm}}
An [[O]](n
insertionSort(array A)
for i = 1 to length[A]-1 do
Line 14:
=={{header|Ada}}==
<
procedure Insertion_Sort(Item : in out Data_Array) is
Line 32:
end loop;
end Insertion_Sort;
</
=={{header|ALGOL 68}}==
{{trans|Ada}}
Line 104:
=={{header|Common Lisp}}==
<
(let ((tail (member-if-not predicate list)))
(values (ldiff list tail) tail)))
Line 117:
(defun insertion-sort (list)
(reduce #'insert list :initial-value nil))
</
=={{header|D}}==
<
void insertionSort(T)(T[] A) {
Line 142:
writefln(a2);
}
</
=={{header|Forth}}==
<pre>
Line 166:
=={{header|Fortran}}==
<
SUBROUTINE Insertion_Sort(a)
REAL, INTENT(in out), DIMENSION(:) :: a
Line 182:
END DO
END SUBROUTINE Insertion_Sort
</
In 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
<
DO i = 2, SIZE(a)
j = i - 1
Line 192:
a(j+1:i) = cshift(a(j+1:i),-1)
END DO
</
=={{header|Haskell}}==
<
insert x [] = [x]
insert x (y:ys) | x <= y = x:y:ys
Line 206:
-- *Main> insertionSort [6,8,5,9,3,2,1,4,7]
-- [1,2,3,4,5,6,7,8,9]
</
=={{header|Java}}==
<
public static void insertSort(int[] A){
for(int i = 1; i < A.length; i++){
Line 221:
}
}
</
=={{header|Modula-3}}==
{{trans|Ada}}
<
MODULE InsertSort;
Line 242:
END IntSort;
END InsertSort.
</
=={{header|OCaml}}==
<
[] -> [x]
| y :: ys ->
Line 253:
let insertion_sort lst = List.fold_right insert lst [];;
insertion_sort [6;8;5;9;3;2;1;4;7];;</
=={{header|Perl}}==
<
sub insertion_sort {
$arr = shift;
Line 272:
insertion_sort($a);
print join(' ', @{$a}), "\n";
</
Output:
-31 0 1 2 4 65 83 99 782
Line 300:
=={{header|Python}}==
<
def insertion_sort(l):
for i in xrange(1, len(l)):
Line 309:
j -= 1
l[j+1] = key
</
===Insertion sort with binary search===
<
def insertion_sort_bin(seq):
for i in range(1, len(seq)):
Line 327:
# insert key at position ``low``
seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:]
</
=={{header|Scheme}}==
<
(if (null? lst)
(list x)
Line 345:
(insertion-sort (cdr lst)))))
(insertion-sort '(6 8 5 9 3 2 1 4 7))</
=={{header|UnixPipes}}==
|