import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class Test
{
static public void main(String...alt)
{
StringBuffer[] sb={new StringBuffer("Anil"),new StringBuffer("Ravi"),new StringBuffer("Ali"),new StringBuffer("Ram"),new StringBuffer("Mohan"),new StringBuffer("Anthony")};
out.println("Before Sorting : ");
for(StringBuffer x:sb)
out.print(x+" ");
MyComparator mc=new MyComparator();
Arrays.sort(sb,mc);
out.println("\nAfter Sorting : ");
for(StringBuffer x:sb)
out.print(x+" ");
int result1=Arrays.binarySearch(sb,0,3,"Anil",mc);
out.println("\n\nAnil is available in index : "+result1);
int result2=Arrays.binarySearch(sb,0,3,"Ram",mc);
// Ram is available in array but not available in this range(0-3) in unsorted array.
out.println("Ram is not available So its insertion point is : "+result2);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString(); // Converting StringBuffer->Object to String
String s2=o2.toString(); // Converting StringBuffer->Object to String
return s1.compareTo(s2); //Ascending order
}
}
import java.util.Arrays;
import java.util.Comparator;
class Test
{
static public void main(String...alt)
{
StringBuffer[] sb={new StringBuffer("Anil"),new StringBuffer("Ravi"),new StringBuffer("Ali"),new StringBuffer("Ram"),new StringBuffer("Mohan"),new StringBuffer("Anthony")};
out.println("Before Sorting : ");
for(StringBuffer x:sb)
out.print(x+" ");
MyComparator mc=new MyComparator();
Arrays.sort(sb,mc);
out.println("\nAfter Sorting : ");
for(StringBuffer x:sb)
out.print(x+" ");
int result1=Arrays.binarySearch(sb,0,3,"Anil",mc);
out.println("\n\nAnil is available in index : "+result1);
int result2=Arrays.binarySearch(sb,0,3,"Ram",mc);
// Ram is available in array but not available in this range(0-3) in unsorted array.
out.println("Ram is not available So its insertion point is : "+result2);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString(); // Converting StringBuffer->Object to String
String s2=o2.toString(); // Converting StringBuffer->Object to String
return s1.compareTo(s2); //Ascending order
}
}
0 Comment to "Java Program to search an element in an Object/StringBuffer Array within a range."
Post a Comment