Sorting algorithms/Insertion sort: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: shorten a long literal by one byte, changed a variable name, made a variable global.)
(Thought it might help to include a substantially more efficient version.)
Line 1,674: Line 1,674:
}
}
insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</lang>
insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</lang>

R has native vectorized operations which allow the following, more efficient implementation.

<lang r>
insertion_sort <- function(x) {
for (j in 2:length(x)) {
key <- x[j]
bp <- which.max(x[1:j] > key)
if (bp == 1) {
if (key < ar[1]){
x <- c(key, ar[-j])
}
}
else {
x <- x[-j]
x <- c(ar[1:bp - 1], key, x[bp : (s-1)])
}
return(x)
}
}
</lang>


=={{header|Racket}}==
=={{header|Racket}}==