sorting - Selection Sort Algorithm in R -
i need understand type of code , action happens here. instance, take vector x defined integer (8,6,5,4,2,1,9).
the first step of function check if condition given, length of vector higher 1. x, condition given. next step highlight position of smallest value in vector, 6. dont understand happens in next steps , why has combine vector?
selsort <- function(x) { if(length(x) > 1) { mini <- which.min(x) c(x[mini], selsort(x[-mini])) #selsort() somewhere in here -> recursion } else x }
in recursion, there 2 key cases:
base case - input produces result directly
recursive case - input causes program call again
in function, base case when length of x not greater 1. when happens, return x. when reach base case, not running function more times, track through of previous recursive cases finish executing selsort()
calls.
the recursive case when length greater 1. this, combine smallest value in our vector result of selsort()
without smallest value. continue until reach base case. so, find smallest value, remove list, , repeat of values previous run except 1 selected. once reach base case of there being 1 element left (the largest one), have no more minimum finding do, return last element.
this called selection sort, because selecting 1 element each time (the smallest element). large data, inefficient, natural way think sorting.
there more efficient sorting algorithms. 1 nice 1 easy understand merge sort: merge sort in r
Comments
Post a Comment