简单数组排序和折半查找
程序员文章站
2024-03-20 17:53:34
...
f1(),f2(),f3(),,,分别是三种排序方法,其实平常用的话还是感觉第一个好记忆,三者区别是,运行速度不同,,
importjava.util.Scanner;
public class sort{
public static voidmain(String[] args) {
intN=10;
int[] a=newint[N];
for(inti=0;i
a[i]=(int)(Math.random()*(100+0));
}
System.out.println("输出未排序数组");
for(inti=0;i
System.out.print(""+a[i]);
}
f3(a);
System.out.println("输出排序后数组");
for(inti=0;i
System.out.print(a[i]+ " ");
}
Scanner sc=newScanner(System.in);
intx=sc.nextInt();
intn=f4(a,x,N-1);
if(n<0){
System.out.println("没找到您要找的数:"+x);
}else{
System.out.println("您要找的数是:"+x+"在第"+(n+1)+"位");
}
}
public static voidf(int[] a)
{ inttemp;
for(inti=0;i
for(intj=a.length-1;j>i;j--){
if(a[j-1]>a[j]){
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
}
public static voidf2(int [] a){
intk,i,j,tmp=0;
for(i=0;i
k=i;
for(j=i;j
if(a[j]>a[k]){
k=j;
}
}
tmp=a[i];
a[i]=a[k];
a[k]=tmp;
}
}
public static voidf3(int[] a){
inti,j,t;
for(i=1;i
t=a[i];
j=i-1;
while(j>=0&& t
a[j+1]=a[j];
j--;
}
a[j+1]=t;
}
}
public static intf4(int[] a,int x,int n){
intlow,mid,high;
low=0;
high=n;
while(low<=high){
mid=(low+high)/2;
if(x==a[mid]){return mid;
}elseif(x>a[mid]){
low = mid+1;
}else{high =mid-1;}
}
return-1;
}
}
注:此代码小编测试过了,,喜欢请关注,会努力更新更多!