# Get the indices of an array after sorting

Your challenge today is to write a program or function which takes a list l and gives the positions in l at which each successive element of l sorted appears.

In other words, output the index of the smallest value, followed by the index of the second smallest value, etc.

You can assume that the input array will contain only positive integers, and will contain at least one element.

Test cases:

Input                  | Output (1-indexed)
[7, 4, 5]              | [2, 3, 1]
[1, 2, 3]              | [1, 2, 3]
[2, 6, 1, 9, 1, 2, 3]  | [3, 5, 1, 6, 7, 2, 4]
[4]                    | [1]


When two or more elements with the same value appear, their indices should appear next to each other from smallest to largest.

This is , fewest bytes wins!

• -1 for a trivial challenge that can be solved with built-ins in common golfing languages, and for accepting an answer in less than 24 hours. This was neither a fair challenge, nor an interesting one. Commented Jul 30, 2017 at 11:44
• Well, I get why he accepted an answer within 24 hours, it's impossible to beat. Commented Jul 30, 2017 at 14:28
• @CodyGray I thought downvoting when I saw the 1-2 bytes answer, but actually, I don't think it's a bad challenge for more standard programming languages. Of course, it's not a hard challenge, but still, there is definitely some golfing possibilities. Of course, it's unpleasant to see 1-byte built-ins, but I don't think that it's fair to blame the challenge for that.
Commented Jul 30, 2017 at 16:07
• Using a 1 character builtin is hardly practice. Easy doesn't necessarily mean solvable using only builtins.
Commented Jul 31, 2017 at 7:36
• The best solution in such cases is to forget about te accept feature, which isn't really relevant anyway here. Commented Jul 31, 2017 at 9:01

# Dyalog APL, 1 byte

⍋


Dyalog APL has a built in operator function (thank you Zacharý for clearing this up) to do this.

## Example

⍋11 2 4 15
2 3 1 4
{⍵[⍋⍵]}11 4 2 15
2 4 11 15


Here I'm indexing into the list by the sorted indices to return the list in ascending order.

• Oh, just to alert you to some confusing terminology, in APL, builtins like ⍋ are considered functions, while things like ¨⍨⍣.∘/\⌿⍀⌸⍤ are operators. Commented Jul 30, 2017 at 15:45
• polyglot with BQN. Commented Dec 31, 2021 at 7:39

# Jelly, 1 byte

Ụ


Try it online!

• Heh that was too obvious... Commented Jul 30, 2017 at 8:25
• APL deserved this one, +1 though for your speed. Commented Jul 30, 2017 at 14:25
• @Zacharý I'm sure Jelly picked this one up from J, which in turn inherited it from APL.
Commented Aug 17, 2017 at 12:51

1-indexed:

import Data.List
map snd.sort.(zip[1..])


Try it online!

-1 byte thanks to @ØrjanJohansen!

• Pointfree version saves one byte: map snd.sort.(zip[1..]). Commented Jul 30, 2017 at 5:56

# Python 2, 56 bytes

This solution is 0-indexed. This abuses the fact that sorted() creates a copy of the original list.

l=input()
for k in sorted(l):a=l.index(k);print a;l[a]=0


Try it online!

• Why did you ungolf this? Commented Jul 30, 2017 at 9:11
• @EriktheOutgolfer Fixed, Rollback. Commented Jul 30, 2017 at 9:13

# Javascript (ES6), 39 bytes

-2 bytes thanks to @powelles

This only works in browsers where Array.prototype.sort is stable.

a=>[...a.keys()].sort((b,c)=>a[b]-a[c])


1-indexed version (47 bytes):

a=>a.map((_,i)=>i+1).sort((b,c)=>a[b-1]-a[c-1])


Example code snippet:

f=
a=>[...a.keys()].sort((b,c)=>a[b]-a[c])
console.log("7,4,5 => "+f([7,4,5]))
console.log("1,2,3 => "+f([1,2,3]))
console.log("2,6,1,9,1,2,3 => "+f([2,6,1,9,1,2,3]))
console.log("4 -> "+f([4]))

• [...a.keys()] instead of a.map((_,i)=>i) will save you a couple of bytes. Commented Jul 30, 2017 at 18:32

# Python 2, 48 bytes

lambda x:sorted(range(len(x)),key=x.__getitem__)


Try it online!

• Nice, I got outgolfed >_<. I switched my answer to Python 3 such that I don't feel that bad Commented Jul 30, 2017 at 9:06
• @Mr.Xcoder Well, that's his job...
– Neil
Commented Jul 30, 2017 at 9:14
• @Mr.Xcoder Come on, you shouldn't feel bad for that! You made a full program, I made a function, and my approach is a bit different. Commented Jul 30, 2017 at 9:14
• I don't feel bad, I knew this will appear (I personally hate the __<blahblah>__ syntax). I will do some Jelly, I don't want to lose my training :) Commented Jul 30, 2017 at 9:16
• @Mr.Xcoder Codegolf doesn't mean pretty syntax and formatting. ;) Commented Jul 30, 2017 at 9:17

# Perl 6,  27  21 bytes

*.pairs.sort(*.value)».key


Test it

->\x{sort {x[$_]},^x}  Test it Inspired by a Python answer ## Expanded: -> # pointy block lambda \x # declare sigilless parameter { sort { x[$_] },  # sort by the value in ｢x｣ at the given position
^x          # Range up-to the number of elements in ｢x｣
}


# Bash + coreutils, 20

nl|sort -nk2|cut -f1


# Swift 4, 82 bytes

func f(l:[Int]){var l=l;for k in l.sorted(){let a=l.index(of:k)!;print(a);l[a]=0}}


Test Suite.

## Explanation

In Swift, l.sorted() creates a sorted copy of the original Array. We loop through the sorted elements in the list and after printing each item's index in the original Array with let a=l.index(of:k)!;print(a), and then, in order to keep the correct indexes in the Array, we assign l[a] to 0, because it does not affect our normal output.

Take note that this is 0-indexed, since it is a port of my Python solution. If you want it to be 1-indexed, replace print(a) with print(a+1) or Try it online!.

# J, 2 bytes

/:


Try it online!

Zero-based indexing.

• Was going to post this... Commented Aug 1, 2017 at 4:19

# R, 5 bytes

There is a builtin function for this.

order

• Standard rules is to provide a program of function. order is already a function, so you don't have to handle input using scan(). This would be 5 bytes.
Commented Jul 31, 2017 at 7:34
• rank() would save a byte Commented Aug 1, 2017 at 15:10
• I am sure there was a rank answer by @JarkoDubbeldam, but I do not see it anymore. Commented Aug 1, 2017 at 16:58
• Correct, it does not follow the spec so I deleted it.
Commented Aug 1, 2017 at 17:02

# Ruby, 40 bytes

->a{a.zip([*1..a.size]).sort.map &:last}


Try it online!

# Octave, 17 bytes

@(i)[~,y]=sort(i)


Try it online!

Octave is like MATLAB but with inline assignment, making things possible that gives the folks at Mathworks HQ headaches. It doesn't matter what you call y, but you can't do without that dummy variable, as far as I know.

# Julia, 8 bytes

sortperm


Attempt This Online!

# MATL, 2 bytes

&S


Try it online!

Input and output are implicit.

# MY, 3 bytes

MY also has a builtin for this!

⎕⍋↵


Try it online!

### How?

Evaluated input, grade up, then output with a newline.

Indexed however you set the index, with ⌶/0x48. (Can even be some weird integer like -1 or 2, the default is 1).

# Java 8, 128 + 19 = 147 bytes

Based on Mr. Xcoder's solution. 0-based. Lambda takes input as an Integer[] and returns Integer[]. Byte count includes lambda expression and required import.

import java.util.*;


l->{Integer o[]=l.clone(),s[]=l.clone(),i=0;for(Arrays.sort(s);i<l.length;)l[o[i]=Arrays.asList(l).indexOf(s[i++])]=0;return o;}


Try It Online

## Ungolfed lambda

l -> {
Integer
o[] = l.clone(),
s[] = l.clone(),
i = 0
;
for (Arrays.sort(s); i < l.length; )
l[o[i] = Arrays.asList(l).indexOf(s[i++])] = 0;
return o;
}


## Notes

I use Integer[] instead of int[] to allow use of Arrays.asList, which has no primitive versions. Integer is preferred to Long because values are used as array indices and would require casting.

This ended up being shorter than my best procedural-style List solution because of the cost of class and method names.

This also beat a solution I tried that streamed the inputs, mapped to (value, index) pairs, sorted on values, and mapped to indices, mostly because of the baggage needed to collect the stream.

## Acknowledgments

• -5 bytes thanks to Nevay
• You don't need j: l->{Integer o[]=l.clone(),s[]=l.clone(),i=0;for(Arrays.sort(s);i<l.length;l[o[i]=Arrays.asList(l).indexOf(s[i++])]=0);return o;} (19+128 bytes). Commented Aug 16, 2017 at 18:23

# Factor, 8 bytes

arg-sort


Try it online!

0-indexed

# Common Lisp, 82 bytes

(lambda(l)(loop as i in(sort(copy-seq l)'<)do(setf(elt l(print(position i l)))0)))


Try it online!

## Clojure, 39 bytes

#(map key(sort-by val(zipmap(range)%)))

• Translated to Perl 6 {map *.key,(sort *.value,(0..* Z=> @_))} Commented Jul 30, 2017 at 13:51

# CJam, 12 bytes

{ee{1=}\$0f=}


Try it online!

# MATLAB / Octave, 29 bytes

[~,y]=sort(input(''));disp(y)


Try it online!

• While your answer is perfect MATLAB, you can actually do inline assignment in anonymous functions in Octave. Commented Jul 30, 2017 at 14:18
• Good one! I knew about in-line assignment, but I didn't know you could output directly like that Commented Jul 30, 2017 at 15:06
• To be honest, me neither. I started with something like @(X)([~,y]=sort(X)), and while I was looking of a way to get y from this, I realized y was actually the return value from the assignment, and closer inspection revealed that brackets weren't even needed. MATLAB likes everything explicit; Octave is happy when it's unambiguous. Commented Jul 30, 2017 at 15:40

## JavaScript (ES6), 69 bytes

0-indexed. Works for lists containing up to 65,536 elements.

a=>[...a=a.map((n,i)=>n<<16|i)].sort((a,b)=>a-b).map(n=>a.indexOf(n))


### Test cases

let f =

a=>[...a=a.map((n,i)=>n<<16|i)].sort((a,b)=>a-b).map(n=>a.indexOf(n))

console.log(JSON.stringify(f([7, 4, 5])))
console.log(JSON.stringify(f([1, 2, 3])))
console.log(JSON.stringify(f([2, 6, 1, 9, 1, 2, 3])))
console.log(JSON.stringify(f([4])))

• Can you change n=>a.indexOf(n) to just a.indexOf? Commented Jul 30, 2017 at 15:33
• @Zacharý Unfortunately not. A method of an instanced object cannot be used as a callback. Commented Jul 30, 2017 at 15:36
• @Zacharý Even worse is that Array#map passes 3 arguments to the callback function, and Array#indexOf expects 2, so it will give undesirable results. Commented Jul 31, 2017 at 4:56

# Python 3, 52 bytes

lambda l:list(zip(*sorted(zip(l,range(len(l))))))[1]


Try it online!

# Husk, 10 7 bytes

This is a direct port of my Haskell answer, also 1-indexed:

m→Oz,N


Try it online!

### Ungolfed/Explained

Code        Description               Example
-- implicit input            [2,6,1]
N  -- natural numbers           [1,2,3,..]
z,   -- zip, but keep input left  [(2,1),(6,2),(1,3)]
O      -- sort                      [(1,3),(2,1),(6,2)]
m→       -- keep only indices         [3,1,2]


# Java (OpenJDK 8), 72 bytes

l->l.stream().sorted().map(i->{int j=l.indexOf(i);l.set(j,0);return j;})


Try it online!

Takes a List<Integer>, returns a Stream<Integer> containing the results.

We get a Stream based off the initial list, sort it, then map each number to it's index in the list. In order to accommodate duplicate elements, we set the original element in the list to 0.

# SmileBASIC, 67 bytes

DEF I(A)DIM B[0]FOR I=1TO LEN(A)PUSH B,I
NEXT
SORT A,B
RETURN B
END


Very simple, all it does is generate a list of numbers from 1 to (length of array) and sort this by the same order as the input.

# Python 3 with Numpy, 38 26 bytes

12 bytes saved thanks to Jo King (no need to give the function a name)

import numpy
numpy.argsort


Output is 0-based.

Try it online!

• The function could just be numpy.argsort without the lambda part
– Jo King
Commented Nov 6, 2018 at 5:21
• @JoKing Thanks for the suggestion. I wrote it that way because with just numpy.argsort;import numpy I get an error (numpy has not been imported yet), and with import numpy;numpy.argsort I need to move f= to the code part. Do you know that the standard procedure is in these cases? Move the f= and not count it? Commented Nov 6, 2018 at 10:36
• Yeah, I guess. Maybe just redefine f=numpy.argsort in the footer
– Jo King
Commented Nov 6, 2018 at 10:42
• @JoKing Good idea. Done. Thanks! Commented Nov 6, 2018 at 11:26

# Vyxal, 1 byte

⇧


Try It Online!

0-indexed

# Thunno 2, 1 byte

ƙ


Try it online!

Same as the other golflangs - built-in for "grade up".