1.二分查找(非递归)
package diguei; public class Ex012202 { public static int Fn(int x,int str[]) { int low=0; int high=str.length-1; while(low<=high) { int m=(low+high)/2; if(x==str[m]) { return m; }else if (x<str[m]) { high=m; }else { low=m; } } return -1; } public static void main(String[] args) { int s[]= {1,2,3,56,85,95,15,26,75}; int y=85; Ex012202 ex012202=new Ex012202(); int index=ex012202.Fn(y, s); if(index==-1) { System.out.println("没有找到该元素!"); }else { System.out.println("查找元素的下标为:"+index); } } }
2.二分查找(递归)
package diguei; public class Ex012203 { public static void main(String[] args) { int s[]= {1,2,3,16,18,25,35,46,75}; int y=35; Ex012203 ex012203=new Ex012203(); int index=ex012203.Fn(0, s.length-1, y, s); if(index==-1) { System.out.println("没有找到该元素!"); }else { System.out.println("查找元素的下标为:"+index); } } public static int Fn(int low,int high,int mid,int[] str) { if(low>high) { return -1; } int m=(low+high)/2; if(mid==str[m]) { return m; }else if (mid<str[m]) { return Fn(low, m-1, mid, str); }else { return Fn(m+1, high, mid, str); } } }
3.递归冒泡排序(递归)
将数组划分成两部分 [0 .. j] [j +1 .. a.length-1]
左边[0 .. j] 是未排序部分
右边 [j+1 .. a.length-1] 是已排序部分
未排序区间内,相邻的两个元素比较,如果前一个大于后一个,则交换位置
package diguei; public class Ex012204 { public static void f(int[] str,int j) { if(j==0) { return; } for(int i=0;i<j;i++) { if(str[i]>str[i+1]) { int t=str[i]; str[i]=str[i+1]; str[i+1]=t; } } f(str, j-1); } public static void main(String[] args) { int[] a= {7,6,5,4,3,2,1}; f(a, a.length-1); for(int i=0;i<a.length;i++) { System.out.print(a[i]); } } }
4.递归冒泡排序(递归)改进
package diguei; public class Ex012204 { public static void f(int[] str,int j) { if(j==0) { return; } int x=0; for(int i=0;i<j;i++) { if(str[i]>str[i+1]) { int t=str[i]; str[i]=str[i+1]; str[i+1]=t; x=i; } } f(str, x); } public static void main(String[] args) { int[] a= {7,6,5,4,2,3,1}; f(a, a.length-1); for(int i=0;i<a.length;i++) { System.out.print(a[i]); } } }
5.插入排序(递归)
package diguei; public class Ex012205 { public static void F(int[] str,int low) {//low未排序区域第一个 if(low==str.length) { return; } int t=str[low]; int i=low-1;//已排序区域指针 while(i>=0&&str[i]>t) {//没有找到插入位置 str[i+1]=str[i];//空出插入位置 i--; } //找到插入位置 str[i+1]=t; F(str, low+1); } public static void main(String[] args) { int[] a= {1,2,3,4,8,7,6,5}; F(a, 1); for(int i=0;i<a.length;i++) { System.out.print(a[i]); } } }
6.多路递归-斐波那契(兔子问题)
第一个月,有一对未成熟的兔子 (黑色,注意图中个头较
第二个月,它们成熟
第三个月,它们能产下一对新的小兔子 (蓝色)。所有兔子遵循相同规律
求第 n 个月的兔子数?(对)
f(6) = f(5) + 上个月成熟的兔子
f(6)=f(5)+f(4)
7. 多路递归-斐波那契(青蛙跳台阶)
楼梯有n阶
青蛙要爬到楼顶,可以一次跳一阶,也可以一次跳两阶只能向上跳
问有多少种跳法?