sort¶
Sorts a vector by algebraic value. Optionally, a vector can be sorted by absolute value, and a sort permutation can be returned.
Synopsis¶
sort (x)
Required Arguments¶
- float
x
(Input) - Input vector to be sorted.
Return Value¶
A vector of length n
containing the values of the input vector x
sorted into ascending order. If an error occurs, then None
is returned.
Optional Arguments¶
absolute
- Sort
x
by absolute value. permutation
(Output)- Return the sort permutation.
Description¶
By default, sort
sorts the elements of x
into ascending order by
algebraic value. The vector is divided into two parts by choosing a central
element T
of the vector. The first and last elements of x
are
compared with T
and exchanged until the three values appear in the vector
in ascending order. The elements of the vector are rearranged until all
elements greater than or equal to the central elements appear in the second
part of the vector and all those less than or equal to the central element
appear in the first part. The upper and lower subscripts of one of the
segments are saved, and the process continues iteratively on the other
segment. When one segment is finally sorted, the process begins again by
retrieving the subscripts of another unsorted portion of the vector. On
completion, \(x_j\leq x_i\) for \(j<i\). If the option absolute
is selected, the elements of x
are sorted into ascending order by
absolute value. If we denote the return vector by y, on completion,
\(|y_j|\leq|y_i|\) for \(j<i\).
If the option permutation
is chosen, a record of the permutations to the
array x
is returned. That is, after the initialization of
\(\text{permutation}_i=i\), the elements of permutation
are moved in
the same manner as are the elements of x
.
Examples¶
Example 1¶
In this example, an input vector is sorted algebraically.
from numpy import *
from pyimsl.math.sort import sort
from pyimsl.math.writeMatrix import writeMatrix
x = [1.0, 3.0, -2.0, 4.0]
sorted_result = sort(x)
writeMatrix("Sorted vector", sorted_result)
Output¶
Sorted vector
1 2 3 4
-2 1 3 4
Example 2¶
This example sorts an input vector by absolute value and prints the result stored in user-allocated space.
from numpy import *
from pyimsl.math.sort import sort
from pyimsl.math.writeMatrix import writeMatrix
x = [1.0, 3.0, -2.0, 4.0]
sorted_result = sort(x, absolute=True)
writeMatrix("Sorted vector", sorted_result)
Output¶
Sorted vector
1 2 3 4
1 -2 3 4