Sort By Height

Description


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.

Example

For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] array.integer a

If a[i] = -1, then the i^{th} position is occupied by a tree. Otherwise a[i] is the height of a person standing in the i^{th} position.

Guaranteed constraints: 5 ≤ a.length ≤ 15, -1 ≤ a[i] ≤ 200.

  • [output] integer

Sorted array a with all the trees untouched.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function sortByHeight(a) {
    var b = a.slice();
    var pos = [];
    var i = -1;
    while ((i = a.indexOf(-1, i+1)) > -1) {
        pos.push(i);
    }
    var rpos = pos.slice();
    while(rpos.length){
        b.splice(rpos.pop(), 1);
    } 

    b.sort((a,b)=>a-b);
    while(pos.length) {
        b.splice(pos.shift(), 0, -1);
    }
    return b;
}