view gnv-artifacts/src/main/java/de/intevation/gnv/jfreechart/LevelOrderIndices.java @ 496:f14c5d1b5b71

Issue142. Paid attention on array length. Parameters without values resulted in ArrayIndexOutOfBoundsExceptions. gnv-artifacts/trunk@576 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Ingo Weinzierl <ingo.weinzierl@intevation.de>
date Tue, 19 Jan 2010 16:47:25 +0000
parents 20a480753ff9
children c4156275c1e1
line wrap: on
line source
package de.intevation.gnv.jfreechart;

import java.util.LinkedList;

/**
 * @author Sascha L. Teichmann (sascha.teichmann@intevation.de)
 */
public class LevelOrderIndices
{
    public interface Visitor {
        Object visit(int index);
    }

    protected int from;
    protected int to;

    public LevelOrderIndices() {
    }

    public LevelOrderIndices(int to) {
        this(0, to);
    }

    public LevelOrderIndices(int from, int to) {
        this.from = Math.min(from, to);
        this.to   = Math.max(from, to);
    }

    public Object visit(Visitor visitor) {
        LinkedList<int[]> queue = new LinkedList<int[]>();

        queue.add(new int [] { from, to });

        while (!queue.isEmpty()) {
            int [] pair = queue.remove();

            int mid = (pair[0] + pair[1]) >> 1;

            Object result = visitor.visit(mid);

            if (result != null) {
                return result;
            }

            if (mid-1 >= pair[0]) {
                queue.add(new int [] { pair[0], mid-1 });
            }

            if (mid+1 <= pair[1]) {
                pair[0] = mid+1;
                queue.add(pair);
            }
        }

        return null;
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :

http://dive4elements.wald.intevation.org