# simple sorting algorithm for a sequence of variables that cannot be contained in an array. Useful for organizing formulated Price Targets at a specific bar/event or other sequencing needs.
#
# Script by Jphilli11
# Notes:
# 1) Max variables supported (as is) is 10.
# 2) lowest position is 0, highest is 9
# 3) duplicate values will be assinged the same position value and will be the greater of the 2 potential positions.
# e.g. [ 1, 2, 2, -1 ]
# [ 2 ] will be assigned position #3 in both cases and position #2 will be "empty"
# 4) Once position values are assigned they can easily be sorted/ranked for use later:
# if v1p == 0 then ...else
# if v2p == 0 .... etc etc.
declare upper;
def _bn = if !isnan(close) then barnumber() else _bn[1];
def _end = highestall(_bn);
def v1 = 1;
def v2 = 80;
def v3 = -4;
def v4 = 1.8;
script PainfulSort{
input v1 = 99999.99; #assign 9999.99 to any unspecified value
input v2 = 99999.99;
input v3 = 99999.99;
input v4 = 99999.99;
input v5 = 99999.99;
input v6 = 99999.99;
input v7 = 99999.99;
input v8 = 99999.99;
input v9 = 99999.99;
input v0 = 99999.99;
def r1 = v1 < v2; #if the primary is less than next, increment 1
def r2 = v1 < v3;
def r3 = v1 < v4;
def r4 = v1 < v5;
def r5 = v1 < v6;
def r6 = v1 < v7;
def r7 = v1 < v8;
def r8 = v1 < v9;
def r9 = v1 < v0;
#sum all increments to determine relative position in the list
plot result = r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9;
#end script
};
#iterate through each variable as the primary for comparison.
#first position in each script call should be the next variable in the sequence to evaluate.
#subtract from 10 as 10 is the maximum variables calculated (whether or not we're sorting 10).
def v1p = 10 - (PainfulSort(v1, v2, v3, v4)."result");
def v2p = 10 - (PainfulSort(v2, v1, v3, v4)."result");
def v3p = 10 - (PainfulSort(v3, v2, v1, v4)."result");
def v4p = 10 - (PainfulSort(v4, v2, v1, v1)."result");
#continue calling sort for each variable in the sequence. this example is only sorting 4
#display the results
addchartbubble(_bn == _end, close,
"V1: " + v1 + " Pos: " + v1p +
"\n V2: " + v2 + " Pos: " + v2p +
"\n V3: " + v3 + " Pos: " + v3p +
"\n V4: " + v4 + " Pos: " + v4p
,color.yellow, yes);