java算法每日一练2021/1/23

1.顺序查找

/**
* 顺序查找
* 时间复杂度O(n)
* @param args
*/
public static void main(String[] args) {
int[] nums = {1,1,5,13,6,9,8};
System.out.println("该数值所在下标为:"+search(nums,13));
}
public static int search(int[] nums, int num){
int length = nums.length;
for(int i = 0; i < length; i++){
if(num == nums[i]){
return i;
}
}
return -1;
}
2.二分查找
/**
* 二分查找 时间复杂度O(logn),存储结构必须是顺序存储 ,数据有序
* @param args
*/
public static void main(String[] args) {
int[] nums = {1,2,3,6,7,8,10};
System.out.println("该数值所在下标为:"+search(nums,13));
}
public static int search(int[] nums, int num){
int low = 1;
int high = nums.length-1;
while(low<=high) {
int mid = (low+high)/2;
if(nums[mid]<num)
low=mid+1; //要+1
else if(nums[mid]>num)
high=mid-1; //要-1
else
return mid;
}
return -1;
}
3.插值查找
/**
* 插值查找,对于表长较大,关键字分布比较均匀的查找表来说,可以采用
* @param args
*/
public static void main(String[] args) {
int[] nums = {1,2,3,6,7,8,10};
System.out.println("该数值所在下标为:"+search(nums,7));
}
public static int search(int[] nums, int num){
int low = 1;
int high = nums.length-1;
while(low<=high) {
int mid = low + (high - low) * (num - nums[low]) / (nums[high] - nums[low]);/*插值*/
if(nums[mid]<num)
low=mid+1; //要+1
else if(nums[mid]>num)
high=mid-1; //要-1
else
return mid;
}
return -1;
}
4.斐波那契查找
/*
* 斐波那契数列
* 采用递归
*/
public static int fib(int n) {
if(n==0)
return 0;
if(n==1)
return 1;
return fib(n-1)+fib(n-2);
}

/*
* 斐波那契数列
* 不采用递归
*/
public static int fib2(int n) {
int a=0;
int b=1;
if(n==0)
return a;
if(n==1)
return b;
int c=0;
for(int i=2;i<=n;i++) {
c=a+b;
a=b;
b=c;
}
return c;
}

/*
* 斐波那契查找
*/
public static int fibSearch(int[] arr,int n,int key) {
int low=1; //记录从1开始
int high=n; //high不用等于fib(k)-1,效果相同
int mid;

int k=0;
while(n>fib(k)-1) //获取k值
k++;
int[] temp = new int[fib(k)]; //因为无法直接对原数组arr[]增加长度,所以定义一个新的数组
System.arraycopy(arr, 0, temp, 0, arr.length); //采用System.arraycopy()进行数组间的赋值
for(int i=n+1;i<=fib(k)-1;i++) //对数组中新增的位置进行赋值
temp[i]=temp[n];

while(low<=high) {
mid=low+fib(k-1)-1;
if(temp[mid]>key) {
high=mid-1;
k=k-1;
}else if(temp[mid]<key) {
low=mid+1;
k=k-2;
}else {
if(mid<=n)
return mid;
else
return n; //当mid位于新增的数组中时,返回n
}
}
return 0;
}
public static void main(String[] args) {
int[] arr = {0,1,16,24,35,47,59,62,73,88,99};
int n=10;
int key=59;
System.out.println(fibSearch(arr, n, key));
}

posted on 2021-01-23 09:56  孟庆淋  阅读(94)  评论(0编辑  收藏  举报

导航