This was kinda interesting because I was needing to write a script to do the exact same thing.
The script I wrote will change the formatting from a horizantal reading sort in a grid to a vertical sort in a grid, which isn't straightforward when the data is in a linear array.
A B C D
E F G H
I J
becomes
A D G J
B E H
C F I
The way I thought of to do it is to increment the counter by the number of rows. If it goes above the number of elements (n), that means a new row if reached and subtract by (n-1) to get one more. The wording is a little off, but anyways, here's the PHP script I went ahead and wrote. It's in PHP since that's what I'm using (and I needed this anyways).
Arguments:
$array --- input linear array of sorted values
$col --- number of columns to output (rows will be calculated)
$pad --- value to put in empty cells. To switch, it is needed for the array to be able to fit a rectangle, thus some empty values may be needed. (See reordering above and look at blank spaces and notice the blank spaces.) The script forces the output array to be a rectangle by appending blank values.
Output:
linear array of values. Using the letters for example:
{A, D, G, J, B, E, H, ' ', C, F, I, ' '}
Script:
(Note: NOT debugged yet and written in notepad.)
Code:
function $out = reorder_array( $array, $col, $pad ) {
$num = count($array_in);
$row = ceil($num/$col);
$in = array_pad( $array, $row*col, $pad );
$num = $row*col-1; //Highest index
$out = array();
for($i=0; $i!=$num; $i+=$row) {
if($i>=$num) $i-=$num;
$out[] = $in[$i];
}
return $out
}
This will reformat the array and let you print in the same manner you would for a horizontal sort.
This may not be the most efficient way