之前学C语言时对递归有了较多了解,这部分主要把题目的代码都自己实现一遍。知识点不再记录了
import java.io.File;
import java.util.Scanner;
public class ComputeFactorial {
public static void main(String[] args) {
// TODO Auto-generated method stub
String directory = "f:\java";
System.out.println(getSize(new File(directory)) + " bytes") ;
double [] list = { 2.5,1,5,8,3.1,5.5,6.8};
recursionSort(list);
for (double e:list)
System.out.println(e);
System.out.println("key = 3.1 , after BinarySearch fine the index = " + recursiveBinarySearch(list,3.1) );
String s = "II I";
System.out.println(" ""+s +" " is isPalindrome = " + isPalindrome(s));
int fibonacci_index = 10;
System.out.println(" while index = " + fibonacci_index + " ,the fibonacci data = " + fibonacci(fibonacci_index));
int factorialN = 5;
System.out.println(" while N = " + factorialN + " ,the factorial result = " + factorial(factorialN));
}
private static long getSize(File file) {
long size = 0;
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; files != null && i < files.length; i++)
size += getSize(files[i]);
}
else size += file.length();
return size;
}
public static int recursiveBinarySearch(double []list, double key) {
int low = 0;
int high = list.length-1;
return recursiveBinarySearch(list,low,high,key);
}
private static int recursiveBinarySearch(double []list, int low, int high, double key) {
if (low > high) return -low-1;
int mid = (low+high)/2;
if(key < list[mid])
return recursiveBinarySearch(list,low,mid-1,key);
else if(key > list[mid])
return recursiveBinarySearch(list,mid+1,high,key);
else
return mid ;
}
/* -------- sort ------- */
public static void recursionSort(double []list) {
recursionSort(list,0,list.length-1);
}
private static void recursionSort(double []list,int low,int high) {
if(low<high) {
int indexMin = low;
double min = list[low];
for(int i = low+1; i<= high; i++) {
if(list[i] < min) {
min = list[i];
indexMin = i;
}
}
list[indexMin] = list[low];
list[low] = min;
recursionSort(list,low+1,high);
}
}
/* --- isPalindrome --- */
public static boolean isPalindrome(String s) {
return isPalindrome(s,0,s.length()-1);
}
private static boolean isPalindrome(String s,int low,int high) {
if(low>= high) return true;
else if(s.charAt(low) != s.charAt(high))
return false;
else return isPalindrome(s,low+1,high-1);
}
/* --- fibonacci --- */
public static int fibonacci(int index) {
if(index==0) return 0;
else if(index==1) return 1;
else return fibonacci(index-1)+fibonacci(index-2);
}
/* --- factorial --- */
public static long factorial(int n) {
if(n==0) return 1;
else return n*factorial(n-1);
}
}