开发者

Java - this sorting method is a mystery

im stuck with the following code, it should insert a key/pointer combination into a node of a datastucture and keep it in a sorted order, however the order seems random and i just CANT figure out whats wrong!

public void add (int val, Node no) {
    // Find the index where to insert
    int maxval = 0;
    for (int o = 0; o < this.values.length; o++)
        if (val < this.values[o]) {
            maxval = o;
            break;
        }
    // Move all the data from the chosen index one spot forward
    for (int o = this.values.length-1; o > maxval; o--) {
        this.values[o] = this.values[o-1];
        t开发者_开发问答his.children[o] = this.children[o-1];
    }
    // Insert the value
    this.children[maxval] = no;
    this.values[maxval] = val;
}


Well one problem is that if val is greater than all the current values, you end up with maxval = 0. You could fix this by initializing maxval to values.length - 1 to start with, perhaps...

Another problem is that you're effectively losing the original value of values[values.length - 1] - it's being overwritten with the earlier value, but nothing's copying that value elsewhere. What's the desired behaviour here?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜