日期:2014-05-20 浏览次数:20791 次
public class SearchTest
{
public static void main(String[] args)
{
int[] arr = {1,5,4,3,9,7};
Sort.sortUp(arr);
for(int i = 0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
int[] arr2 = {1,5,4,3,9,7};
System.out.println("index="+Sort.search(arr2,9));
System.out.println("index="+Sort.search2(arr,9));
}
}
class Sort
{
public static int search2(int[] array,int value)
{
int start = 0;
int end = array.length-1;
int middle;
while(end >= start)
{
middle = (start + end)/2;
System.out.println(middle);
if(value == array[middle])
{
return middle;
}
//value > array[middle]?(start = middle+1):(end = middle-1);//为什么不能用三元表达式
if(value < array[middle])
{
end = middle - 1;
}
if(value > array[middle])
{
start = middle + 1;
}
}
return -1;
}
public static int search(int[] array,int value)
{
if(array != null)
{
for(int i = 0;i < array.length ; i++)
{
if(array[i] == value)
{
return i;
}
}
}
return -1;
}
public static int[] sortUp(int[] array)
{
for(int i=0;i<array.length-1;i++)
{
for(int j= 0;j<array.length-1-i;j++)
{
if(array[j]>array[j+1])
{
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
return array;
}
}