//排序,找最值
class ArrDemo
{
public static void main(String[] args)
{
int [] arr={1,5,6,9,12,15,19,23};
int max=getMax(arr);
int min=getMin(arr);
System.out.println("max="+max);
System.out.println("min="+min);
printArr(arr);
selectSort(arr);
bubbleSort(arr);
printArr(arr);
int a=halfsearch(arr,11);
System.out.println(a);
}
//折半查找,数组必须是有顺序的
public static int halfsearch(int[]arr,int a)
{
int min=0,max=arr.length,mid;
mid=(min+max)/2;
while (min<=max)
{ mid=(min+max)/2;
if (a>arr[mid])
min=mid+1;
else if(a<arr[mid])
max=mid-1;
else
return mid;
}
return -1;
}
private static void compare(int[]arr,int a,int b)
{
if (arr[a]>arr[b])
{
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
}
//找最大值
public static int getMax(int []arr)
{
int max=arr[0];
for (int i=1;i<arr.length ;i++ )
{
if(arr[i]>max)
{
max=arr[i];
}
}
return max;
}
//找最小值
public static int getMin(int[]arr)
{
int min=arr[0];
for (int j=1;j<arr.length ;j++ )
{
if(arr[j]<min)
min=arr[j];
}
return min;
}
//选择排序
public static void selectSort(int[]arr)
{
for (int i=0;i<arr.length-1 ;i++ )
{
for (int j=i+1; j<arr.length; j++)
{
compare(arr,i,j);
}
}
}
public static void printArr(int[]arr)
{
System.out.print("[");
for (int i=0;i<arr.length ;i++ )
{
if (i!=arr.length-1)
System.out.print(arr[i]+",");
else
System.out.print(arr[i]+"]");
}
System.out.println();
}
//冒泡排序
public static void bubbleSort(int[]arr)
{
for (int i=1;i<arr.length+1 ;i++ )
{
for (int j=0;j<arr.length-1-i ;j++ )
{
compare(arr,y,y+1);
}
}
}
}
|