Created
April 2, 2015 19:25
-
-
Save SleeplessByte/3748e6ffe26ac90b9df6 to your computer and use it in GitHub Desktop.
Mainly for use with ArrayList to keep it sorted at insertion time. This method runs in `log(n)` time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the `RandomAccess` interface and is large, this method will do an iterator-based binary search that performs `O(n)` link tr…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final int NOT_UNIQUE = -1; | |
/** | |
* Adds an item in a list using it's comparable sort | |
* | |
* @param item the item to add | |
* @param list the list to add to | |
* @param uniq if true, reject duplicates | |
* @param <A> if | |
* @param <I> | |
* @param <L> | |
* @return | |
*/ | |
public static <A extends I, I extends Comparable<I>, L extends List<I>> int sortedAdd( A item, L list, boolean uniq ) { | |
int size = list.size(); | |
int location = Collections.binarySearch( list, item ); | |
if ( location > 0 ) { | |
if ( uniq ) | |
return NOT_UNIQUE; | |
for ( ; location < size; location++ ) | |
if ( list.get( location ) != item ) | |
break; | |
} else { | |
location = -location - 1; | |
} | |
list.add( location, item ); | |
return location; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment