Sort By Height
Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180]
, the output should be
sort_by_height(a) = [-1, 150, 160, 170, -1, -1, 180, 190]
Solution
py
def sort_by_height(a):
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i] != -1 and a[j] != -1 and a[i] > a[j]:
a[i], a[j] = a[j], a[i]
return a
print(sort_by_height([-1, 150, 190, 170, -1, -1, 160, 180]))
js
function sortByHeight(a) {
const sorted = a.filter((x) => x !== -1).sort((x, y) => x - y);
return a.map((x) => (x === -1 ? x : sorted.shift()));
}
console.log(sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]));