R/sortList_OfNumericVectors.R

Defines functions sortList_OfNumericVectors

Documented in sortList_OfNumericVectors

#' Sort a list of numeric vectors.
#' 
#' Sort list of numeric vectors using bubble sort approach. 
#' In this function order is defined by the left-most member of the numeric vector that differs between the two neighbouring vectors. For example [c(1,1,1), c(1,1,2), c(1,2,1)] is in order but [c(1,1,1), c(1,2,1), c(1,1,2)] is not (becasue the left-most number differing is 2 in the second element which should be a third element to be considered ordered).
#' A numeric vector supersedes (comes after) another numeric vector if the left-most differeing number between the two vectors is higher in value.
#' Otherwise vector remains in its place.
#' 
#' The bubble sort algorithm is as follows:
#' For lst of size n, with j=n-1 pairwise (duplex) comparisons
#' 1. Compare lst[[1]]  and lst[[2]]. If lst[[1]] is bigger than lst[[2]], swap the elements
#' 2. Move to the next element, lst[[2]] (which might now contain the result of a swap from the previous step), and compare it with lst[[3]]. If lst[[2]] is bigger than lst[[3]], swap the elements. Do this for every pair of elements until j comparison.
#' 3. Update j=j-1
#' 4. Repeat steps 1 & 2 until j=0
#' This sort is possiable because after each traverse the largest element is bubbled to the end of the lst. 
#' For more info about bubble sort see: https://brilliant.org/wiki/sorting-algorithms/ 
#' 
#' @param lst List of to-be-sorted numeric vectors
#' @return Vector of indexes that can be used for sorting (comparable to the output of order function)
#' @export 
#' 

sortList_OfNumericVectors = function(lst) {
  duplexes = create.duplexes(length(lst))
  # count of rows equals the number of comparisons to be performed before first lst traverse 
  j = nrow(duplexes)
  while(j>0){
    for(i in 1:j){
      # comparing two adjacent elements 
      whichOneIsLarger = compareNumericVectors(lst[duplexes[i,]])
      # swapping if first element is greater than second
      if(whichOneIsLarger==1){
        lst[duplexes[i,]] = lst[rev(duplexes[i,])]
      }
    }
  # decrementing numer of comparisons
  j = j-1
  }
  lst
}
msxakk89/dat documentation built on Aug. 3, 2020, 6:39 p.m.