Skip to content

Instantly share code, notes, and snippets.

@lizettepreiss
Created October 30, 2018 05:36
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 lizettepreiss/529f88832054435d2138a89123f91547 to your computer and use it in GitHub Desktop.
Save lizettepreiss/529f88832054435d2138a89123f91547 to your computer and use it in GitHub Desktop.
Demo of java Collections.binarySearch(..)
package preiss.collectionsBinarySort;
// Java program to demonstrate working of Collections.
// binarySearch()
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsTest {
public static void main(String[] args)
{
List al = new ArrayList();
al.add(2);
al.add(3);
al.add(10);
al.add(20);
//to get insertion point for elements not present: add 1 to answer and then multiply by -1
System.out.println("list size: " + al.size());
System.out.println();
int index = Collections.binarySearch(al, 2);
System.out.println("2 is at position: " + index);
index = Collections.binarySearch(al, 3);
System.out.println("3 is at position: " + index);
// 10 is present at index 2.
index = Collections.binarySearch(al, 10);
System.out.println("10 is at position: " + index);
index = Collections.binarySearch(al, 20);
System.out.println("20 is at position: " + index);
System.out.println();
index = Collections.binarySearch(al, 0);
System.out.println("0 would be at position: " + index);
index = Collections.binarySearch(al, 1);
System.out.println("1 would be at position: " + index);
// 15 is not present. 15 would have been inserted
// at position 3. So the function returns (-4-1)
// which is -4. ie (-insertion point - 1)
index = Collections.binarySearch(al, 15);
System.out.println("15 would be at position: " + index);
index = Collections.binarySearch(al, 25);
System.out.println("25 would be at position: " + index);
index = Collections.binarySearch(al, 35);
System.out.println("35 would be at position: " + index);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment