• Introduction
  • Getting Started
    • Resources
  • Variables
    • Allowed Variable Names
    • Stylistic Conventions
  • Integers and Floating-Point Numbers
    • Integers
    • Floating-Point Numbers
    • Arbitrary Precision Arithmetic
    • Numeric Literal Coefficients
    • Literal zero and one
  • Mathematical Operations and Elementary Functions
    • Arithmetic Operators
    • Bitwise Operators
    • Updating operators
    • Numeric Comparisons
    • Elementary Functions
  • Complex and Rational Numbers
    • Complex Numbers
    • Rational Numbers
  • Strings
    • Characters
    • String Basics
    • Unicode and UTF-8
    • Interpolation
    • Common Operations
    • Non-Standard String Literals
    • Regular Expressions
    • Byte Array Literals
    • Version Number Literals
  • Functions
    • Argument Passing Behavior
    • The return Keyword
    • Operators Are Functions
    • Operators With Special Names
    • Anonymous Functions
    • Multiple Return Values
    • Varargs Functions
    • Optional Arguments
    • Keyword Arguments
    • Evaluation Scope of Default Values
    • Do-Block Syntax for Function Arguments
    • Further Reading
  • Control Flow
    • Compound Expressions
    • Conditional Evaluation
    • Short-Circuit Evaluation
    • Repeated Evaluation: Loops
    • Exception Handling
    • Tasks (aka Coroutines)
  • Scope of Variables
    • For Loops and Comprehensions
    • Constants
  • Types
    • Type Declarations
    • Abstract Types
    • Bits Types
    • Composite Types
    • Immutable Composite Types
    • Declared Types
    • Tuple Types
    • Type Unions
    • Parametric Types
    • Type Aliases
    • Operations on Types
  • Methods
    • Defining Methods
    • Method Ambiguities
    • Parametric Methods
    • Note on Optional and keyword Arguments
  • Constructors
    • Outer Constructor Methods
    • Inner Constructor Methods
    • Incomplete Initialization
    • Parametric Constructors
    • Case Study: Rational
  • Conversion and Promotion
    • Conversion
    • Promotion
  • Modules
    • Summary of module usage
  • Metaprogramming
    • Program representation
    • Expressions and evaluation
    • Macros
    • Code Generation
    • Non-Standard String Literals
  • Multi-dimensional Arrays
    • Arrays
    • Sparse Matrices
  • Linear algebra
    • Matrix factorizations
    • Special matrices
  • Networking and Streams
    • Basic Stream I/O
    • Text I/O
    • Working with Files
    • A simple TCP example
    • Resolving IP Addresses
  • Parallel Computing
    • Code Availability and Loading Packages
    • Data Movement
    • Parallel Map and Loops
    • Synchronization With Remote References
    • Scheduling
    • Distributed Arrays
    • Constructing Distributed Arrays
    • Distributed Array Operations
    • Shared Arrays (Experimental)
    • ClusterManagers
  • Running External Programs
    • Interpolation
    • Quoting
    • Pipelines
  • Calling C and Fortran Code
    • Mapping C Types to Julia
    • Accessing Data through a Pointer
    • Passing Pointers for Modifying Inputs
    • Garbage Collection Safety
    • Non-constant Function Specifications
    • Indirect Calls
    • Calling Convention
    • Accessing Global Variables
    • Passing Julia Callback Functions to C
    • C++
    • Handling Platform Variations
  • Interacting With Julia
    • The different prompt modes
    • Key bindings
    • Tab completion
  • Embedding Julia
    • High-Level Embedding
    • Converting Types
    • Calling Julia Functions
    • Memory Management
    • Working with Arrays
    • Exceptions
  • Packages
    • Package Status
    • Adding and Removing Packages
    • Installing Unregistered Packages
    • Updating Packages
    • Checkout, Pin and Free
  • Package Development
    • Initial Setup
    • Making changes to an existing package
    • Creating a new Package
    • Tagging Package Versions
    • Fixing Package Requirements
    • Requirements Specification
  • Profiling
    • Basic usage
    • Accumulation and clearing
    • Options for controlling the display of profile results
    • Configuration
  • Memory allocation analysis
  • Performance Tips
    • Avoid global variables
    • Measure performance with @time and pay attention to memory allocation
    • Tools
    • Avoid containers with abstract type parameters
    • Type declarations
    • Break functions into multiple definitions
    • Write “type-stable” functions
    • Avoid changing the type of a variable
    • Separate kernel functions
    • Access arrays in memory order, along columns
    • Pre-allocating outputs
    • Avoid string interpolation for I/O
    • Optimize network I/O during parallel execution
    • Fix deprecation warnings
    • Tweaks
    • Performance Annotations
  • Workflow Tips
    • REPL-based workflow
    • Browser-based workflow
  • Style Guide
    • Write functions, not just scripts
    • Avoid writing overly-specific types
    • Handle excess argument diversity in the caller
    • Append ! to names of functions that modify their arguments
    • Avoid strange type Unions
    • Try to avoid nullable fields
    • Avoid elaborate container types
    • Use naming conventions consistent with Julia’s base/
    • Don’t overuse try-catch
    • Don’t parenthesize conditions
    • Don’t overuse ...
    • Don’t use unnecessary static parameters
    • Avoid confusion about whether something is an instance or a type
    • Don’t overuse macros
    • Don’t expose unsafe operations at the interface level
    • Don’t overload methods of base container types
    • Be careful with type equality
    • Do not write x->f(x)
  • Frequently Asked Questions
    • Sessions and the REPL
    • Functions
    • Types, type declarations, and constructors
    • Nothingness and missing values
    • Memory
    • Julia Releases
  • Noteworthy Differences from other Languages
    • Noteworthy differences from MATLAB
    • Noteworthy differences from R
    • Noteworthy differences from Python
  • Unicode Input
  • Essentials
    • Introduction
    • Getting Around
    • All Objects
    • Types
    • Generic Functions
    • Syntax
    • System
    • Errors
    • Events
    • Reflection
    • Internals
  • Collections and Data Structures
    • Iteration
    • General Collections
    • Iterable Collections
    • Indexable Collections
    • Associative Collections
    • Set-Like Collections
    • Dequeues
    • PriorityQueue
    • Heap Functions
  • Mathematics
    • Mathematical Operators
    • Mathematical Functions
    • Statistics
    • Signal Processing
    • Numerical Integration
  • Numbers
    • Standard Numeric Types
    • Data Formats
    • Numbers
    • BigFloats
    • Random Numbers
  • Strings
  • Arrays
    • Basic functions
    • Constructors
    • Mathematical operators and functions
    • Indexing, Assignment, and Concatenation
    • Array functions
    • Combinatorics
    • BitArrays
    • Sparse Matrices
  • Tasks and Parallel Computing
    • Tasks
    • General Parallel Computing Support
    • Distributed Arrays
    • Shared Arrays (Experimental, UNIX-only feature)
  • Linear Algebra
    • Standard Functions
    • BLAS Functions
  • Constants
  • Filesystem
  • I/O and Network
    • General I/O
    • Network I/O
    • Text I/O
    • Multimedia I/O
    • Memory-mapped I/O
  • Punctuation
  • Sorting and Related Functions
    • Sorting Functions
    • Order-Related Functions
    • Sorting Algorithms
  • Package Manager Functions
  • Collections and Data Structures
    • Iteration
    • General Collections
    • Iterable Collections
    • Indexable Collections
    • Associative Collections
    • Set-Like Collections
    • Dequeues
    • PriorityQueue
    • Heap Functions
  • Graphics
    • Geometry
  • Unit and Functional Testing
    • Overview
    • Handlers
    • Macros
    • Functions
  • Testing Base Julia
  • C Interface
  • Profiling
  • Reflection and introspection
  • Documentation of Julia’s Internals
    • Base.Cartesian
    • System Image Building
  • Developing/debugging Julia’s C code
    • Reporting and analyzing crashes (segfaults)
    • gdb debugging tips
 
Julia Language
  • Docs »
  • Sorting and Related Functions
  • View page source

Sorting and Related Functions¶

Julia has an extensive, flexible API for sorting and interacting with already-sorted arrays of values. For many users, sorting in standard ascending order, letting Julia pick reasonable default algorithms will be sufficient:

julia>sort([2,3,1])3-elementArray{Int64,1}:123

You can easily sort in reverse order as well:

julia>sort([2,3,1],rev=true)3-elementArray{Int64,1}:321

To sort an array in-place, use the “bang” version of the sort function:

julia>a=[2,3,1];julia>sort!(a);julia>a3-elementArray{Int64,1}:123

Instead of directly sorting an array, you can compute a permutation of the array’s indices that puts the array into sorted order:

julia>v=randn(5)5-elementArray{Float64,1}:0.2972880.382396-0.597634-0.0104452-0.839027julia>p=sortperm(v)5-elementArray{Int64,1}:53412julia>v[p]5-elementArray{Float64,1}:-0.839027-0.597634-0.01044520.2972880.382396

Arrays can easily be sorted acording to an arbitrary transformation of their values:

julia>sort(v,by=abs)5-elementArray{Float64,1}:-0.01044520.2972880.382396-0.597634-0.839027

Or in reverse order by a transformation:

julia>sort(v,by=abs,rev=true)5-elementArray{Float64,1}:-0.839027-0.5976340.3823960.297288-0.0104452

Reasonable sorting algorithms are used by default, but you can choose other algorithms as well:

julia>sort(v,alg=InsertionSort)5-elementArray{Float64,1}:-0.839027-0.597634-0.01044520.2972880.382396

Sorting Functions¶

sort!(v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Sort the vector v in place. QuickSort is used by default for numeric arrays while MergeSort is used for other arrays. You can specify an algorithm to use via the alg keyword (see Sorting Algorithms for available algorithms). The by keyword lets you provide a function that will be applied to each element before comparison; the lt keyword allows providing a custom “less than” function; use rev=true to reverse the sorting order. These options are independent and can be used together in all possible combinations: if both by and lt are specified, the lt function is applied to the result of the by function; rev=true reverses whatever ordering specified via the by and lt keywords.

sort(v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Variant of sort! that returns a sorted copy of v leaving v itself unmodified.

sort(A, dim, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])

Sort a multidimensional array A along the given dimension.

sortperm(v, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Return a permutation vector of indices of v that puts it in sorted order. Specify alg to choose a particular sorting algorithm (see Sorting Algorithms). MergeSort is used by default, and since it is stable, the resulting permutation will be the lexicographically first one that puts the input array into sorted order – i.e. indices of equal elements appear in ascending order. If you choose a non-stable sorting algorithm such as QuickSort, a different permutation that puts the array into order may be returned. The order is specified using the same keywords as sort!.

sortrows(A, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Sort the rows of matrix A lexicographically.

sortcols(A, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Sort the columns of matrix A lexicographically.

Order-Related Functions¶

issorted(v, [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Test whether a vector is in sorted order. The by, lt and rev keywords modify what order is considered to be sorted just as they do for sort.

searchsorted(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Returns the range of indices of a which compare as equal to x according to the order specified by the by, lt and rev keywords, assuming that a is already sorted in that order. Returns an empty range located at the insertion point if a does not contain values equal to x.

searchsortedfirst(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Returns the index of the first value in a greater than or equal to x, according to the specified order. Returns length(a)+1 if x is greater than all values in a.

searchsortedlast(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Returns the index of the last value in a less than or equal to x, according to the specified order. Returns 0 if x is less than all values in a.

select!(v, k, [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Partially sort the vector v in place, according to the order specified by by, lt and rev so that the value at index k (or range of adjacent values if k is a range) occurs at the position where it would appear if the array were fully sorted. If k is a single index, that values is returned; if k is a range, an array of values at those indices is returned. Note that select! does not fully sort the input array, but does leave the returned elements where they would be if the array were fully sorted.

select(v, k, [by=<transform>,] [lt=<comparison>,] [rev=false])¶

Variant of select! which copies v before partially sorting it, thereby returning the same thing as select! but leaving v unmodified.

Sorting Algorithms¶

There are currently three sorting algorithms available in base Julia:

  • InsertionSort
  • QuickSort
  • MergeSort

InsertionSort is an O(n^2) stable sorting algorithm. It is efficient for very small n, and is used internally by QuickSort.

QuickSort is an O(n log n) sorting algorithm which is in-place, very fast, but not stable – i.e. elements which are considered equal will not remain in the same order in which they originally appeared in the array to be sorted. QuickSort is the default algorithm for numeric values, including integers and floats.

MergeSort is an O(n log n) stable sorting algorithm but is not in-place – it requires a temporary array of equal size to the input array – and is typically not quite as fast as QuickSort. It is the default algorithm for non-numeric data.

The sort functions select a reasonable default algorithm, depending on the type of the array to be sorted. To force a specific algorithm to be used for sort or other soring functions, supply alg=<algorithm> as a keyword argument after the array to be sorted.

Next Previous

Sphinx theme provided by Read the Docs