Sort disjoint sublist
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.
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>