/ sorting using patiencesort idea / algorithm: / find sequences in increasing order and store beginning and end points. / Then keep switching from one array to the other as you merge. findruns:{[x] y: (-1), -':x : & y < 0 } merge:{[myarr1; myarr2] out: ((#myarr1) + (#myarr2)) # 0 i: 0 i1: 0 i2: 0 while[(i < #out) & (i1 < #myarr1) & (i2 < #myarr2) f: myarr1[i1] < myarr2[i2] if[f; out[i]: myarr1[i1]; i+: 1; i1+: 1] if[~f; out[i]: myarr2[i2]; i+: 1; i2+: 1] ] if[i1 = #myarr1 left: (#myarr2) - i2 out[i+!left]: myarr2[i2+!left] ] if[i2 = #myarr2 left: (#myarr1) - i1 out[i+!left]: myarr1[i1+!left] ] :out } / go from array 1 to array 2 merge1to2:{[] i:0 newstartpoints: () while[i < (#startpoints) - 2; i1: startpoints[i] i2: startpoints[i+1] i3: startpoints[i+2] newstartpoints,: i1 i1all: i1 + !(i2-i1) i2all: i2 + !(i3-i2) iitot: i1 + !(i3-i1) arr2[iitot]:: merge[arr1[i1all]; arr1[i2all]] i+: 2 ] if[i = (#startpoints) - 1; ii: startpoints[i] + !((#arr1) - startpoints[i]) newstartpoints,: startpoints[i] arr2[ii]:: arr1[ii] ] if[i = (#startpoints) - 2; i1: startpoints[i] i2: startpoints[i+1] i3: #arr1 newstartpoints,: i1 i1all: i1 + !(i2-i1) i2all: i2 + !(i3-i2) iitot: i1 + !(i3-i1) arr2[iitot]:: merge[arr1[i1all]; arr1[i2all]] ] startpoints:: newstartpoints } / go from array 2 to array 1 merge2to1:{[] i:0 newstartpoints: () while[i < (#startpoints) - 2; i1: startpoints[i] i2: startpoints[i+1] i3: startpoints[i+2] newstartpoints,: i1 i1all: i1 + !(i2-i1) i2all: i2 + !(i3-i2) iitot: i1 + !(i3-i1) arr1[iitot]:: merge[arr2[i1all]; arr2[i2all]] i+: 2 ] if[i = (#startpoints) - 1; ii: startpoints[i] + !((#arr2) - startpoints[i]) newstartpoints,: startpoints[i] arr1[ii]:: arr2[ii] ] if[i = (#startpoints) - 2; i1: startpoints[i] i2: startpoints[i+1] i3: #arr2 newstartpoints,: i1 i1all: i1 + !(i2-i1) i2all: i2 + !(i3-i2) iitot: i1 + !(i3-i1) arr1[iitot]:: merge[arr2[i1all]; arr2[i2all]] ] startpoints:: newstartpoints } / DATA n: 2000 arr1: n _draw 300 arr2: (#arr1) # 0 arr1 arr2 / EXECUTION startpoints: findruns[arr1] startpoints flag1to2: 1 / go from arr1 to array 2 while[ (1 < #startpoints); if[flag1to2 = 1; merge1to2[]] if[flag1to2 = 0; merge2to1[]] startpoints flag1to2: 1 - flag1to2 ] if[flag1to2 = 1; out: arr1] if[flag1to2 = 0; out: arr2] out