public class Practice5_19{
public static int max(int[] array){
int max=0;
for(int i=0;i<array.length;i++){
if(array[i]>max){
max=array[i];
}
}
return max;
}
public static int indexOf(int[] array,int key){
for(int i=0;i<array.length;i++){
if(array[i]==key){
return i;
}
}
return (-1);
}
public static double average(int[] array){
double ave=0.0;
double sum=0.0;
int max=0;
int min=array[0];
for(int i=0;i<array.length;i++){
if(array[i]>max){
max=array[i];
}
}
for(int i=0;i<array.length;i++){
if(array[i]<min){
min=array[i];
}
}
for(int i=0;i<array.length;i++){
sum=sum+array[i];
}
//System.out.println(max);
//System.out.println(min);
sum=sum-max-min;
//System.out.println(sum);
ave=sum/(array.length-2);
return ave;
}
public static int binarySearch(int[] array,int key){
int left=0;
int right=array.length-1;
while(left<=right){
int mid=(left+right)/2;//int mid=left+(rigght-left)/2;避免越界
if(key>array[mid]){
left=mid+1;
}
else if(key<array[mid]){
right=mid-1;
}else{
return mid;
}
}
return (-1);
}
public static void swap(int[] array,int i,int j){
int t=array[i];
array[i]=array[i+1];
array[i+1]=t;
}
public static void bubbleSort(int[] array){
for(int i=0;i<array.length;i++){
boolean isSwapped=false;
for(int j=0;j<array.length-i-1;j++){
if(array[j]>array[j+1]){
swap(array,j,j+1);
isSwapped=true;
}
}
if(!isSwapped){
return;
}
}
}
public static void main(String[] args){
int[] array={1,4,8,9,13};
int maxValue=max(array);
System.out.println("最大值是 " + maxValue);
int index=indexOf(array,8);
if(index!=(-1)){
System.out.println("0的下标是 " + index);
}else{
System.out.println("没找到");
}
double ret=average(array);
System.out.println("平均值为 " + ret);
int binary=binarySearch(array,0);
if(binary!=-1){
System.out.println("找到了,下标为"+binary);
}else{
System.out.println("没找到");
}
int[] array1=new int[]{6,0,7,2,3,4};
bubbleSort(array1);
//System.out.println(Arrays.toString(array1));
for(int g=0;g<array1.length;g++){
System.out.print(array1[g]);
}
}
}
原文地址:https://blog.51cto.com/14232274/2399299