def rank_selection(random, population, args):
    """Return a rank-based sampling of individuals from the population.
    
    This function behaves similarly to fitness proportionate selection,
    except that it uses the individual's rank in the population, rather
    than its raw fitness value, to determine its probability. This
    means that it can be used for both maximization and minimization 
    problems, since higher rank can be defined correctly for both.
    
    .. Arguments:
       random -- the random number generator object
       population -- the population of individuals
       args -- a dictionary of keyword arguments

    Optional keyword arguments in args:
    
    - *num_selected* -- the number of individuals to be selected (default 1)
    
    """
    num_selected = args.setdefault('num_selected', 1)
    len_pop = len(population)
    population.sort()
    psum = list(range(len_pop))
    den = len_pop * (len_pop + 1) / 2.0
    for i in range(len_pop):
        psum[i] = (i + 1) / den
    for i in range(1, len_pop):
        psum[i] += psum[i - 1]
    selected = []
    for _ in range(num_selected):
        cutoff = random.random()
        lower = 0
        upper = len_pop - 1
        while upper >= lower:
            mid = (lower + upper) // 2
            if psum[mid] > cutoff:
                upper = mid - 1
            else:
                lower = mid + 1
        lower = max(0, min(len_pop - 1, lower))
        selected.append(population[lower])
    return selected
