# Sorting Column Data

QUESTION: I have a 3 column by 10 row data set of XYZ values. I want to sort the data by the X values in the first column but, of course, the corresponding Y and Z values must follow the sorted X value around. How can I do this in IDL?

ANSWER: Consider this random data set:

```   seed = -1L
data = Fix(RandomU(seed, 3, 10) * 100)
Print, data
41       9      75
52      93      38
65       6      72
67      38      63
88      51      65
23      26      76
75      90       7
27      89      27
51      35      24
48      84      83
```

The IDL Sort command is a function that returns not the sorted data, but an index into the original data set that can be used to sort the data. For example, consider this simple example:

```   seed = 1L
a = Fix(RandomU(seed, 10) * 100)
b = Sort(a)
Print, a
Print, b
41  9 75 52 93 38 65  6 72 67
7  1  5  0  3  6  9  8  2  4
sortedArray = a[b]
Print, sortedArray
6  9 38 41 52 65 67 72 75 93
```

Here the sorted array is obtained by subscripting the original array by the index number returned from the Sort command.

We use the same idea to sort the three column data set. We take the index numbers obtained from sorting the first column and use those to sort all three columns. This keeps the corresponding XYZ values together. The solution looks like this. First, sort the first column of data:

```   sortIndex = Sort( data[0,*] )
```

Then sort all three columns with the same index.

```   FOR j=0,2 DO data[j, *] = data[j, sortIndex]
Print, data
23      26      76
27      89      27
41       9      75
48      84      83
51      35      24
52      93      38
65       6      72
67      38      63
75      90       7
88      51      65
```

Hurray! Sorted data.

 Web Coyote's Guide to IDL Programming