递归
找重复->找重复中的变化量->参数变化趋势
数组求和
java
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int n = arr.length;
System.out.println(sum(arr,0,n));
}
public static int sum(int arr[],int start,int end){
if(start == end-1)return arr[start];
else return arr[start] + sum(arr,start+1, end);
}
翻转字符串
java
public static void main(String[] args) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(reversestr(s,0,s.length()));
}
public static StringBuffer reversestr(StringBuffer str,int start,int end){
if(start==end-1){
StringBuffer res = new StringBuffer(String.valueOf(str.charAt(start)));
return res;
}else{
return reversestr(str,start+1,end).append(str.charAt(start));
}
}
斐波那契数列
java
public static void main(String[] args) {
for(int i=1;i<10;i++) System.out.println(fib(i));
}
public static int fib(int n){
if(n==1)return 1;
else if(n==2)return 1;
else return fib(n-1)+fib(n-2);
}
最大公约数
java
public static void main(String[] args) {
System.out.println(gcd(10,20));
}
public static int gcd(int m,int n){
if(n==0)return m;
else return gcd(n,m%n);
}
递归形式进行插入排序
java
public static void main(String[] args) {
int[] arr = {1,5,2,6,3,9,11};
sort1(arr,arr.length-1);
for(int i=0;i<arr.length;i++) System.out.println(arr[i]);
}
public static void sort1(int arr[],int idx){
if(idx==0) return;
else{
sort1(arr,idx-1);
int temp = arr[idx];
int i=idx-1;
while(arr[i]>arr[idx]){
arr[i+1]=arr[i];
i--;
}
arr[i+1]=temp;
}
}
汉诺塔
java
public static void main(String[] args) {
hanoi(3,'a','b','c');
}
public static void hanoi(int n,char c1, char c2, char c3){
if(n==1)System.out.println(""+c1+"->"+c3);
else{
hanoi(n-1,c1,c3,c2);
System.out.println(""+c1+"->"+c3);
hanoi(n-1,c2,c1,c3);
}
}
递归二分查找
java
public static int binarySearch(int[] arr,int target, int low,int high) {
if(low>high)return -1;
int mid = low + (high - low)/2;
if(arr[mid]==target) return mid;
else if(arr[mid]>target)return binarySearch(arr,target,low,mid-1);
else return binarySearch(arr,target,mid+1,high);
}
希尔排序
java
public static void shellSort(int[] arr) {
int n = arr.length;
for(int interval = arr.length/2;interval>0;interval/=2) {
for(int i=interval;i<n;i++) {
int j=i-interval;
int target = arr[i];
while(j>=0&&arr[j]>target) {
arr[j+interval] = arr[j];
j-=interval;
}
arr[j+interval] = target;
}
}
}
算法复杂度
线性、平方、对数