ID:2213872
 
I've coded two sorting functions today:

    mergeSort(list/l)
if(l.len <= 1) return l // list is already sorted
var/mid = floor(l.len/2)
var/list/left = mergeSort(l.Copy(1, mid+1))
var/list/right = mergeSort(l.Copy(mid+1))
var/list/result = new
while(left.len > 0 && right.len > 0)
if(left[1] <= right[1])
result += left[1]
left.Cut(1,2)
else
result += right[1]
right.Cut(1,2)
if(left.len > 0) result += left
else if(right.len > 0) result += right
return result

bubbleSortA(list/l) // everything in this list should be a number
if(!l.len) return
var i, j, temp, num = l.len
for(i=0,i < num, i++)
for(j=1, j < (num - i), j++)
if(l[j] > l[j + 1])
temp = l[j]
l[j] = l[j + 1]
l[j + 1] = temp
return l


Wrote these today, and they are bug free as far as I've tested. After profiling them by running through 20 numbers each time I (spam) click a verb that calls them, and they apparently use 0% CPU. I had no idea sorting could be so easy after the concept is grasped. Feel free to use these in whatever way necessary. If you like math, these are awfully nifty for calculating medians.
Also, to add onto these, are my math procs that I've worked on for data analysis. For whatever use there is, here they are.

    mean(list/l)
if(!islist(l) || !l.len) return
var/total = 0
var/n = l.len
for(var/x in l)
if(!isnum(x)) continue
total += x
return total / n

median(list/l)
if(!islist(l) || !l.len) return
l = mergeSort(l)
if(!(l.len % 2)) return l[(l.len + 1) / 2] // it's odd
else return l[l.len / 2] + l[l.len / 2 + 1]

mode(list/l)
if(!islist(l) || !l.len) return
var/list/keys = list()
for(var/x in l)
if(keys[x]) keys[x]++
else keys[x] = 1
var/num
for(var/x in keys)
if(!num) num = x
else if(keys[num] < keys[x]) num = x
return num

rangeV(list/l)
if(!islist(l) || !l.len) return
l = mergeSort(l)
return l[l.len] - l[1] // largest - smallest = r/range

standardDeviation(list/l, s=0) // s stands for sample, by default it is 0, which implies a population data set
if(!islist(l) || !l.len) return
l = mergeSort(l)
var/mean = mean(l)
var/list/step1 = list()
for(var/x in l)
step1 += (x - mean) ** 2
var/result = 0
for(var/x in step1) result += x
if(!s) result /= l.len
else result /= (l.len - 1)
result = sqrt(result)

variableVariance(list/l, s=0)
if(!islist(l) || !l.len) return
return standardDeviation(l, s) ** 2 // we just square the standard deviation
// since we pass along whether its a sample or population, it's all taken care of



factorial(n, r=0) // keeping r at 0 does a full factorial. Setting it limits the amount of times it runs
if(n == 0) return 0
else if(n == 1) return 1
else if(n == 2) return 2
if(r == 0) r = n
else if(r == 1) return n
else if(r == 2) return n * (n - 1)
var/number = n
for(var/x=1 to (r - 1))
number *= (n - x)
return number
Thank you.
Thank youČ

Login to reply.