Sort disjoint sublist

From Rosetta Code
Revision as of 12:54, 12 February 2011 by Rdm (talk | contribs) (J)
Sort disjoint sublist is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Given a list of values and a list of integer indices into that value list, the task is to sort the values at the given indices, but preserving the values at indices outside the list of those to be sorted.

Make your example work with the following list of values and list of indices:

   values: [7, 6, 5, 4, 3, 2, 1, 0]
   indices: [6, 1, 7]

Where the correct result would be:

   [7, 0, 5, 4, 3, 2, 1, 6].

Note that for one based, rather than the zero-based indexing above, use the indices: [7, 2, 8]. Make your code insensitive to the order of indices given.

J

Note that the task requires us to ignore the order of the indices.

<lang j> 7 6 5 4 3 2 1 0 (/:~@:{`[`]}~ /:~) 6 1 7 7 0 5 4 3 2 1 6 </lang>

Compare this with: <lang j> 6 1 7 /:~@:{`[`]} 7 6 5 4 3 2 1 0 7 1 5 4 3 2 0 6</lang>

Here, the order of the indices specifies the order we want the selected items to be sorted in: 7 1 5 4 3 2 0 6


Python

The function modifies the input data list in-place and follows the Python convention of returning None in such cases.

<lang python>>>> def sort_disjoint_sublist(data, indices): indices = sorted(indices) values = [data[i] for i in indices] values.sort() for index, value in zip(indices, values): data[index] = value


>>> d = [7, 6, 5, 4, 3, 2, 1, 0] >>> i = [6, 1, 7] >>> sort_disjoint_sublist(d, i) >>> d [7, 0, 5, 4, 3, 2, 1, 6]</lang>