Inserts into an ascending sorted list an element. - Android java.util

Android examples for java.util:List Element

Description

Inserts into an ascending sorted list an element.

Demo Code


//package com.book2s;

import java.util.LinkedList;

public class Main {
    /**//from ww  w. ja v  a 2 s. c o  m
     * Inserts into an ascending sorted list an element.
     *
     * Preconditions: The element has to implement the {@code Comparable}
     * interface and the list have to be sorted ascending. Both conditions will
     * not be checked: At runtime a class cast exception will be thrown
     * if the element does not implement the comparable interface and and if the
     * list is not sorted, the element can't be insert sorted.
     *
     * @param <T>     element type
     * @param list
     * @param element
     */
    @SuppressWarnings("unchecked")
    public static <T> void binaryInsert(LinkedList<? super T> list,
            T element) {
        if (list == null) {
            throw new NullPointerException("list == null");
        }

        if (element == null) {
            throw new NullPointerException("element == null");
        }

        boolean isComparable = element instanceof Comparable<?>;

        if (!isComparable) {
            throw new IllegalArgumentException("Not a comparable: "
                    + element);
        }

        int size = list.size();
        int low = 0;
        int high = size - 1;
        int index = size;
        int cmp = 1;

        while ((low <= high) && (cmp > 0)) {
            int mid = (low + high) >>> 1;
            Comparable<? super T> midVal = (Comparable<? super T>) list
                    .get(mid);

            cmp = midVal.compareTo(element);

            if (cmp < 0) {
                low = mid + 1;
            } else if (cmp > 0) {
                high = mid - 1;
            }
        }

        for (int i = low; (i >= 0) && (i < size) && (index == size); i++) {
            Comparable<? super T> elt = (Comparable<? super T>) list.get(i);

            if (elt.compareTo(element) >= 0) {
                index = i;
            }
        }

        list.add(index, element);
    }
}

Related Tutorials