Saturday, 14 November 2015

Find the k Smallest Elements in a List using R

This program is definitely not the most efficient way to find the k smallest elements in a List. But I simply need this now. Improvements might be done later and you are mostly welcome to share any ideas of improvements.

l = c(7,3,6,1,0,2,10,9)

KSmallestElem <- function(DataList, k)
{
  n = length(DataList)
  kmin = {}
  
  initMinIndex = which.min(DataList)
  initMinVal = min(DataList)
  kmin = rbind(kmin,c(initMinIndex,initMinVal))
  
  # 1st level loop:
  #     k times to find the smallest k elemenst
  for(i in 1:k)
  {
    minIndex = 1
    minValue = DataList[1]
    # 2nd level loop:
    #     over the original DataList
    for(j in 1:n)
    {
      if(DataList[j] > kmin[i,2] &&
         DataList[j] < minValue)
      {
        minIndex = j
        minValue = DataList[j]
      }
      
    }
    
    kmin = rbind(kmin,c(minIndex,minValue))
  }
  
  return(kmin)
}


KSmallestElem(l,3)

#################################
Results:
> KSmallestElem(l,3)
     [,1] [,2]
[1,]    5    0
[2,]    4    1
[3,]    6    2
[4,]    2    3









No comments:

Post a Comment