[Question]
  [
Given an unsorted list of unique strictly positive integers, minimally sort it into a 2D matrix. The input list is guaranteed to be of composite length, which means the output matrix is not necessarily square, but is of size `n x m` with `n,m > 1`.
"Minimally sort" here means the following:
* Sort the list in ascending order.
* Compact the output matrix as much as possible -- minimize the sum of the dimensions of the matrix (for example, for `20` input elements as input, a `5x4` or `4x5` output matrix is required, and not a `2x10`).
* Compact the sorted numbers as far to the upper-left of the matrix as possible, starting with the first element in the sorted list.
* This can be thought of as sorting the list, then slicing it along the matrix's anti-diagonals, starting with the upper-left.
## Examples:
For input `1..20` output is either a 5x4 or a 4x5 matrix as follows:
```
 1  2  4  7 11
 3  5  8 12 15
 6  9 13 16 18
10 14 17 19 20
 1  2  4  7
 3  5  8 11
 6  9 12 15
10 13 16 18
14 17 19 20
```
For input `[3, 5, 12, 9, 6, 11]` output is a 2x3 or 3x2 as follows
```
3  5  9
6 11 12
 3  5
 6  9
11 12
```
For input `[14, 20, 200, 33, 12, 1, 7, 99, 58]`, output is a 3x3 as follows
```
 1   7  14
12  20  58
33  99 200
```
For input `1..10` the output should be a 2x5 or 5x2 as follows
```
1 2 4 6  8
3 5 7 9 10
1  2
3  4
5  6
7  8
9 10
```
For input `[5, 9, 33, 65, 12, 7, 80, 42, 48, 30, 11, 57, 69, 92, 91]` output is a 5x3 or 3x5 as follows
```
 5  7 11 33 57
 9 12 42 65 80
30 48 69 91 92
 5  7 11
 9 12 33
30 42 57
48 65 80
69 91 92
```
### Rules
* The input can be assumed to fit in your language's native integer type.
* The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ ~~22~~ 20 bytes
```
pS€ỤỤs
LÆDżṚ$SÞḢç/ịṢ
```
[Try it online!](https://tio.run/##y0rNyan8/78g@FHTmoe7lwBRMZfP4TaXo3se7pylEnx43sMdiw4v13@4u/vhzkX/D7e7//8fbaqjYKmjYGyso2AGZBoa6SiY6yhYGOgomACZJhZAKSDb0FBHwRQobgZUagkUtzSMBQA)
Saved 2 bytes thanks to @[Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
## Explanation
```
pS€ỤỤs  Helper link. Input: integer a (LHS), integer b (RHS)
p       Cartesian product between [1, 2, ..., a] and [1, 2, ..., b]
 S€     Sum each pair
   Ụ    Grade up
    Ụ   Grade up again (Obtains the rank)
     s  Split into slices of length b
LÆDżṚ$SÞḢç/ịṢ  Main link. Input: list A
L              Length
 ÆD            Divisors
     $         Monadic pair
    Ṛ            Reverse
   ż             Interleave
                 Now contains all pairs [a, b] where a*b = len(A)
      SÞ       Sort by sum
        Ḣ      Head (Select the pair with smallest sum)
         ç/    Call helper link
            Ṣ  Sort A
           ị   Index into sorted(A)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~160~~ ~~158~~ ~~153~~ 151 bytes
-2 bytes thanks to Erik the Outgolfer  
-2 bytes thanks to Mr. Xcoder  
```
s=sorted(input())
l=len(s)
x=int(l**.5)
while l%x:x+=1
n=1
o=eval(`l/x*[[]]`)
while s:
 for i in range(l/x)[max(0,n-x):n]:o[i]+=s.pop(0),
 n+=1
print o
```
[Try it online!](https://tio.run/##NY3LDsIgFAX3fMXdmECLtQ8bbRO@hJC0iWhJ8EKgKn59pQsXc1aTOf67Lg7bbYsiurDqGzXoXytljFhhNdLISBIGV2qLouoZ@SzGarCHNKZSNAQzTuj3bOlkT6mQUqnpb8WRwN0FMGAQwowPTbPD5HNOtOZ4TGxENTppVCli5Z2nNeMEcA/7kE/BbZtszhzaeidP13Fo2gyHC4dh4NBf1Q8 "Python 2 – Try It Online") or [Try all test cases](https://tio.run/##TU7tasQgEPx/T7F/ymlue41J0w8Pn0SEC5zpCVZDlNY@faqxgQq6u@PszMw/8e5dt643PcFEAuUHyCeI4JeobxnYZiusdvuQhHGR2KY5DxX4vhurwT4knk6CbZD7q17or9GSq31KjZRKXf9vhGoGk1/AgHGwjO5Dk8yl8nNMpEX3mCh3intp1EmE8@xn0lKsa243m5ccCPwadYhByKrCsGMUZY8wILAO4R3hJXdMoWTPCF1bbn76vv4zhNfMyrThTeEuwhhVhxKwiJeMmwmvlqW/TKQUetmg43H9BQ "Python 2 – Try It Online")
[Answer]
# R ~~110~~ 95 bytes
```
function(x){n=sum(x|1)
X=matrix(x,max(which(!n%%1:n^.5)))
X[order(col(X)+row(X))]=sort(x)
t(X)}
```
[Try it online!](https://tio.run/##LY3bCoMwDEDf/YruQUhZGUatU6H/IYwNxK0ozBaqYmHbt7t4eWiay8mJWzRTi55MM3bWgOcfo4apB/9FHlSqr0fXefCirz3Mbde0cDJhiKV5XCTnhNyse74cNPYNFT87O9PH72qwbiRbMFL5WzRgGUc80NBAIpgUDGPBCsEyypDvA0wFi6P1UUiSnUHBrkQSKvONwxIPkdwMK5gdQiJz2k0pTXMaRaudNqmfEVqsN@na8gc "R – Try It Online")
### How it works
```
f <- function(x) {
  n <- sum(x|1)                           # length
  p <- max(which(!n%%1:n^.5))             # height of matrix
  X <- matrix(x, p)                       # initialize matrix
  X[order(col(X) + row(X))] <- sort(x)    # filling the matrix using position distance to the top left corner
  t(X)                                    # probably required by OP
}
```
[Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) saved a whopping 15(!) bytes by the following tricks
* replacing `length(x)` by `sum(x|1)` (-1 byte)
* `floor()` is not required as `:` rounds down anyway (-7)
* `^.5` is shorter than `sqrt()` (-3)
* using `col(X) + row(X)` instead of `outer` (nice!)
* could not get rid of the `t(X)` though - disappointing ;)
### Original solution
```
function(x){
n=length(x)
p=max(which(!n%%1:floor(sqrt(n))))
X=outer(1:p,1:(n/p),`+`)
X[order(X)]=sort(x)
t(X)}
```
It would look more fancy with `outer` being replaced by `row(X)+col(X)`, but that would require to initialize the output matrix `X` first.
[Try it online!](https://tio.run/##LY1bCsIwEEX/u4r4IUwwYqcva7H7EERQqrGFmtQYURDXXm9bAwkzuWfOuL7XYrsU@mkq31hDb/kJTNlezNXXaIKuvJ3e9KqbqqaZmc@50K21jh5358lInGBX2qe/OOKiU1yQWXVSHRdHBHvrzgh28lA@LHj4PLpvrwFHoQw0VRQrkSrBkRIbJTJULKeAEyWicLh44nhiWIk1SKBpPnJc8F@UjoYBzP5CkDlmE5RJjigc7JjEfwZ0M@zEtv4H "R – Try It Online")
[Answer]
# JavaScript (ES6), 172 bytes
```
l=>(n=l.sort((a,b)=>b-a).length,w=l.findIndex((_,i)=>!(i*i<n|n%i)),a=l=>[...Array(l)],r=a(n/w).map(_=>a(w)),a(w+n/w).map((_,x)=>r.map((s,y)=>x-y in s&&(s[x-y]=l.pop()))),r)
```
## Explanation
```
l=>(                                // Take a list l as input
 l.sort((a,b)=>b-a),                // Sort it
 n=l.length,                        // Get the length n
 w=l.findIndex((_,i)=>!(i*i<n|n%i)),// Find the first integer w where w >= √n and n % w = 0
 a=l=>[...Array(l)],                // Helper function a
 r=a(n/w).map(_=>a(w)),             // Create the grid r of size w, n/w
 a(w+n/w).map((_,x)=>               // For every x from 0 to w + n/w:
  r.map((s,y)=>                     //  For every row s in r:
   x-y in s&&(                      //   If the index x-y is in s:
    s[x-y]=l.pop()))),              //    Set s[x-y] to the next element of l
 r)                                 // Return r
```
## Test Cases
```
f=l=>(n=l.sort((a,b)=>b-a).length,w=l.findIndex((_,i)=>!(i*i<n|n%i)),a=l=>[...Array(l)],r=a(n/w).map(_=>a(w)),a(w+n/w).map((_,x)=>r.map((s,y)=>x-y in s&&(s[x-y]=l.pop()))),r)
l=m=>console.log(JSON.stringify(m))
l(f([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]))
l(f([3,5,12,9,6,11]))
l(f([14,20,200,33,12,1,7,99,58]))
l(f([1,2,3,4,5,6,7,8,9,10]))
```
[Answer]
# [Perl 5](https://www.perl.org/), 132 bytes
```
sub d{$,=0|sqrt(@_=sort{$a-$b}@_);--$,while@_%$,;map{$r++,$c--for@_/$,..$c;$a[$r++][$c--]=$_;$c=++$i,$r=0if$r<0||$c<0||$r>=$,}@_;@a}
```
[Try it online!](https://tio.run/##HcztasIwGIbhU3mQd6A0afNW6wc1khPYETgJtSoGOluTjjFaT32Z7s/954K7O/umiDF8HXEaSGg1hrvvp8bq0Pp@oErS8WHsrJSSxPfVNWdj30iUn1U3kE8SQbWUl9Ybm5FIU6pLqvYvOOxfctBkS6p1kpAT5LVyF/JbNY5U/9fvNInnvzTVI4bqZ2LITp47nKaha1yffYQkE9vdLDJyzLFAgSVWWGMDVmAG5@A5eAEuwEvwCrwGb5Ar5Pzbdr1rbyHK9yJVrP4A "Perl 5 – Try It Online")
Subroutine returns a 2-D array. TIO link includes footer code for displaying test result.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 151 bytes
```
function f(v)n=floor(sqrt(l=nnz(v)));while i=mod(l,n);++n;end;A=nan(m=l/n,n);for k=[1:m 2*m:m:l];do A(k)=sort(v)(++i);until~mod(k+=m-1,m)|k>l;end;A'end
```
Using three different kinds of loop constructs.
[Try it online!](https://tio.run/##LY3LbsMgEEX3/YrZFQJVjF91jKiU74iyiGKjIsOgOo4jVVV/3RliLxhdXc6cidfpMvfLYu94nVxEsGzmaKyPcWS3n3Fi3iD@Usm5fnw734MzIXbMS@RaCNQ9dvpo8IIsGL/HVNs4wmBOqg2Q70IbWn/WXYQjG7i5RXLOnAnhuL7j5Px/0g3ChA8lA/8bvvzqfKe5WEaaPDvzN0qFhEqCyiUcJNSU1NqrUkKepUejKFZESfgkkMiq2bBWbaLqZUhkvQkJbWi5pFg29JUlO61SXxN6SDfp2vIE)
**Unrolled:**
```
function f(v)
    n = floor(sqrt(l=nnz(v)));
    while i = mod(l,n);
        ++n;
    end;
    A = nan(m=l/n, n);
    for k = [1:m 2*m:m:l];
        do
            A(k) = sort(v)(++i);
        until ~mod(k+=m-1, m) | k>l;
    end;
    A'
end
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
ḟȯΛ≤Σ∂MCP¹→←½ḊL
```
This works by brute force, so longer test cases may time out.
[Try it online!](https://tio.run/##AUIAvf9odXNr///huJ/Ir86b4omkzqPiiIJNQ1DCueKGkuKGkMK94biKTP///1szMCwxMSw1Nyw2OSw5Miw5MSw0LDYsNV0 "Husk – Try It Online")
## Explanation
```
ḟȯΛ≤Σ∂MCP¹→←½ḊL  Implicit input, a list of integers x.
              L  Length of x (call it n).
             Ḋ   List of divisors.
            ½    Split at the middle.
          →←     Take last element of first part.
                 This is a divisor d that minimizes d + n/d.
        P¹       List of permutations of x.
      MC         Cut each into slices of length d.
ḟ                Find the first of these matrices that satisfies this:
     ∂            Take anti-diagonals,
    Σ             flatten them,
 ȯΛ≤              check that the result is sorted (each adjacent pair is non-decreasing).
```
[Answer]
# JavaScript (ES6), 233 bytes
```
f=s=>{l=s.length;i=Math.sqrt(l)|0;for(;l%++i;);p=(x)=>(x/i|0+x%i)*l+x%i;m=[...Array(l).keys()].sort((x,y)=>p(x)-p(y));return s.sort((a,b)=>a-b).map((x,i)=>m.indexOf(i)).reduce((a,b,d,g)=>!(d%i)?a.concat([g.slice(d,d+i)]):a,[])}
```
**Explanation**
```
f=s=>{                         // Take array `s` of numbers as input
  l=s.length                   // short-hand for length
  i=Math.sqrt(l)|0             // = Math.floor(Math.sqrt(l))
  for(;l%++i;);                // i = width           
  j=l/i                        // j = height
  p=(x)=>(x/i|0+x%i)*l+x%i     // helper to calculate (sort-of) ~manhattan
                                 // distance (horizontal distance weighted
                                 // slightly stronger), from top-left corner
                                 // to the number x, if numbers 0,...,l are
                                 // arranged left-to-right, top-to-bottom
                                 // in an l=i*j grid
  m=[...Array(l).keys()]         // range array
  .sort((x,y)=>p(x)-p(y)),       // manhatten-sorted, sort-of...
  return s.sort((a,b)=>a-b)      // sort input array by numbers,
    .map((x,i,w)=>w[m.indexOf(i)])    // then apply inverse permutation of the
                                 // range-grid manhatten-sort mapping.
    .reduce(                     // slice result into rows
      (a,b,d,g)=>!(d%i)?a.concat([g.slice(d,d+i)]):a
      ,[]
     )
}
```
[Answer]
# Java 10, ~~199~~ ~~188~~ 186 bytes
```
a->{int j=a.length,m=0,n,i=0,k=0;for(n=m+=Math.sqrt(j);m*n<j;n=j/++m);var R=new int[m][n];for(java.util.Arrays.sort(a);i<m+n;i++)for(j=0;j<=i;j++)if(i-j<n&j<m)R[j][i-j]=a[k++];return R;}
```
[Try it online.](https://tio.run/##dVLBbqMwEL3vV/i0gjKhGEISarxSP6A9pEfkg5eS1g42XeOkqqJ8ezpx2MMqG2Qse@bNzJs31nIvZ/p1e2p7OY7kSSp7@EGIsr5zG9l25Pl8DYZGNIK0UTgRGTO0H/HHNXrpVUueiSWcnOTs1wFBRHOZ9p198@9geAYWFO5bnrHN4CLLTcKfpH9Pxz/ORzpm5s7Wmlmu75PExGwvHVlz232G0kY0VoRAjYTTnVd9@uic/BrTccB4pKNqk1imkiQOMKyja66YRoPaRGqma/tT1yZeN1o0eBVcNtskEcx1fucsWbPjiV36@dj97rGfqa39oF6JQWGiF@@UfWuEjC@i@G700V@K4kAhhwLmUMIClrCCCmgGlALNgRZA50BLoAugS6AroBXk2TGoeJWowBQYVGEeSm9gMF2e4cqgKEIFLFlVUK5u4a/Jnb8b6BL9mHcReCA8g3kO8xUUoaFyCYsKKmQ4xf/7DoJgIeHlrZyPk2Ln0QSjfLBpGwVPHDyEvHyNvjPpsPPpB@rse3s9bD9cZoADn4j/J2qidDx9Aw)
Based on [my answer here](https://codegolf.stackexchange.com/a/163276/52210).
**Explanation:**
```
a->{                        // Method with int-array parameter and int-matrix return-type
  int j=a.length,           //  Length of the input-array
      m=0,n,                //  Amount of rows and columns
      i=0,k=0;              //  Index integers
   for(n=m+=Math.sqrt(j);   //  Set both `m` and `n` to floor(√ `j`)
       m*n<j;               //  Loop as long as `m` multiplied by `n` is not `j`
       n=j/++m);            //   Increase `m` by 1 first with `++m`
                            //   and then set `n` to `j` integer-divided by this new `m`
   var R=new int[m][n];     //  Result-matrix of size `m` by `n`
   for(java.util.Arrays.sort(a);
                            //  Sort the input-array
       i<m+n;)              //  Loop as long as `i` is smaller than `m+n`
     for(j=0;j<=i;j++)      //   Inner loop `j` in range [0,`i`]
       if(i-j<n&j<m)        //    If `i-j` is smaller than `n`, and `j` smaller than `m`
                            //    (So basically check if they are still within bounds)
         R[j][i-j]=a[k++];  //     Add the number of the input array at index `k`,
                            //     to the matrix in the current cell at `[j,i-j]`
  return R;}                //  Return the result-matrix
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~269~~ ~~253~~ 226 bytes
* Saved ~~16~~ ~~43~~ bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
j,w,h,x,y;c(int*a,int*b){a=*a-*b;}f(A,l)int*A;{int B[l];qsort(A,l,4,c);for(w=h=j=2;x=w*h-l;j++)l%j||(w=h,h=j),w=h*h-l?w:j;for(;j=x<w*h;x++)for(y=0;y<=x;y++)x-y<w&y<h?B[x-y+y*w]=*A++:0;for(;j<l;printf("\n%d "+(j++%w>0),B[j]));}
```
[Try it online!](https://tio.run/##dU/LboMwEDy3XxEhpcIwSDav4Bg3Sn6DciBUlCCapEkqQIRvpwvqoYdG8tqrnceOc@cjz8exQoMSLTqVm4fjzcow3XvWZ9rKHGuvhsLcombTdKt6eha7pE7V1/V0uU0IfORMFaeL2ehSV9pVrW6s0qlVZdusXlb3@4SAMAZqJmjTrKtZoirdxsRWLXGnQae56mLdqo4GrdPFzUsXl5tdQr3dWU2qra1tr/mvOq7V@UKZCtN4Oy7fF4Zt0tZl88oZdkmVMqaG8TM7HE3WPz8V5vTFJGW9gAuPkgcIsUIECcEhBIQL4UH4EAFECLGCiCAkXD5QMXX@vl1Nw2Dqr5lHNiSU5CXEgPABjVxdTofD8@ZFtFlKBNEA@UjyT8yB6gE9IAJ5h3Mc4nP4LvwI3vy3YIVQQlJQCimCvx7D@AM "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 214 bytes, using `-zexecstack`-lambdas
* Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for this hackier, yet slimmer version.
```
j,w,h,x,y;f(A,l)int*A;{int B[l];qsort(A,l,4,L"\x62b078bǃ");for(w=h=j=2;x=w*h-l;j++)l%j||(w=h,h=j),w=h*h-l?w:j;for(;j=x<w*h;x++)for(y=0;y<=x;y++)x-y<w&y<h?B[x-y+y*w]=*A++:0;for(;j<l;printf("\n%d "+(j++%w>0),B[j]));}
```
[Try it online!](https://tio.run/##dU/NboJAED63T9GQ2LDwkezyJ@tCjZ77BspBqaiUqhUaoMqpD9e3Kh1MDx5qspOdzPcz3yTWOkm6LkOFDWo0KtUnyNl2VxoTdaLvYTrLY/Ve7I9lj8DFszavfXvJh8Hy@0tjKt0f9SraRFlkqzqqjI2Vq8w0WT7IzuceAWEM1PTQuBplF4nKojoktqqJ2w@aiKsmjGrV0KC2mrB6bMLNeDqj3myMKo6MiWmO@J86zNXhSAFTXZvvBi8PmqnT1kH1xBmmsyxmTLXd22K709np/i7VdeLOYnYSsOHQGR58DBFAQnAIAWFDOBAuhAfhQwwhAggJm7dUTB0@ykLX6N5rM4dsSCjJS4gW/g0audqcHofjXBbRZinhBS3kLck/MVuqG3SPCOTtX@IQn8O14QZwLrd5Q/gSkoJSSOFde7TdT5Lmi3XRWZ@repUU5SJ5/QU "C (gcc) – Try It Online")
]