Skip to content

Instantly share code, notes, and snippets.

@SleeplessByte
Created April 2, 2015 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SleeplessByte/3748e6ffe26ac90b9df6 to your computer and use it in GitHub Desktop.
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…
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