Skip to content
All library documents

Sorting Numeric Arrays While Preserving Original Indices

Article TradingView scripts

Summary

This utility sorts a numeric array in ascending order and returns two aligned outputs: the sorted values and the original positions of those values. It starts with a copy of the input and an index array, then uses nested comparisons and swaps to keep each value paired with its source index. An option reverses both outputs to provide descending order. The included example demonstrates the returned values and indices for a small sample array.

For trading tools, this is a reusable data-handling technique rather than a standalone signal or strategy. Preserving indices lets later logic identify which original series or observation ranked at each position, such as when ordering moving averages or indicator values. The implementation uses a simple quadratic-time comparison sort, so its work grows rapidly as arrays become large. The document supplies no benchmark or trading application results, and users should consider how equal values are ordered if stable ranking matters.

Key ideas

  • The function returns sorted values alongside indices that map back to their original positions.
  • It sorts in ascending order by swapping values and their paired indices.
  • Reversing both outputs provides descending order while retaining the mapping.
  • The nested-loop method has quadratic scaling and no performance benchmark is provided.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.