public class BinSearch
{
private static void swap(int [] num, int i, int j)
{
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
public static int search(String [] a, String x)
{
int low = 0;
int hi = a.length - 1;
int index = -1;
while(low <= hi)
{
int mid = (low + hi) / 2;
if(x.compareTo(a[mid]) < 0)
hi = mid - 1; // to the right
else if( x.compareTo(a[mid]) > 0)
low = mid + 1; // to the left
else
{
// Neither greater than nor less than ...
// ... must be equal
index = mid; // a[mid] is our guy, set index to mid
break;
}
}
return index;
}
static void sort(int[] num)
{
for(int i = 0; i < num.length-1; i++)
{
// First find the index of the largest element
int maxIndex = i;
for(int j = i; j < num.length; j++)
if(num[j] < num[maxIndex])
maxIndex = j;
// Swap the largest with the current position
swap(num, i, maxIndex);
}
}
public static void main(String [] args)
{
// define an string array
String [] num = {"Julian", "Dick", "Ann", "George", "Timmy (the dog)"};
System.out.println("The unsorted array:");
for(int i = 0; i < num.length; i = i + 1)
System.out.print(num[i] + " ");
System.out.println("\n");
// Call the sort method (static method of the Sort class)
sort.sort(num);
System.out.println("The sorted array:");
for(int i = 0; i < num.length; i = i + 1)
System.out.print(num[i] + " ");
System.out.println("\n");
System.out.println("enter a name:");
String x = Console.readString();
System.out.println(x + " is at index ");
System.out.println(search(num, x));
}
}