1.请设计一个程序打印出斐波那契数列(fabnacci)的前20项,请用递归方法!
import java.util.Scanner;
public class fabnacci {
public static int fun(int x){
if(x==1||x==2){
return 1;
}
else{
return fun(x-1)+fun(x-2);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(fun(n));
}
}
2.编写一个程序,运用二维数组来存储和打印杨辉三角(测试时,建议打印10行左右)。
import java.util.Scanner;
public class triangle {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("请输入行数:");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int a[][] = new int[n+1][];
for(int i = 0;i <= n;i++){
a[i] = new int[i+1];
}
for( int i = 0;i <= n;i++){
for(int j = 0;j < a[i].length;j++){
if( i==0 || j==0 || j == a[i].length-1 ){
a[i][j] = 1;
}
else{
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
}
}
for(int i = 0;i <= n;i++){
for(int j = 0;j <= n-i;j++){
System.out.print("\t");
}
for(int j = 0;j < a[i].length;j++){
System.out.print( a[i][j] + "\t\t" );
}
System.out.println();
}
}
}
3…设计一个二分法查询方法,传入一个有序数组和待查找的数据(整形数值),返回查找数据出现的下标位置,没有找到返回-1。
public class binsort {
public static int BinSort(int[] a,int key){
int low = 0,mid = 0,high = a.length-1;
while( low <= high ){
mid = ( low + high )/2;
if( key < a[mid] ){
high = mid-1;
}
else if( key > a[mid] ){
low = mid+1;
}
else{
return mid;
}
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int s[]={2,3,5,6,8,9};
System.out.println(BinSort(s,1));
System.out.println(BinSort(s,2));
}
}
试编写归并排序程序,归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列。排序原理如上图所示,请编写一个方法,传入一个整形数组,完成排序功能!
提示:采用递归思想!
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] nums = {6, 5, 3, 8, 1, 7, 2, 9, 4};
segment(nums, 0, nums.length - 1);
System.out.println(Arrays.toString(nums));
}
private static void segment(int[] nums, int left, int right) {
if (left < right) {
int center = (left + right) / 2;
segment(nums, left, center);
segment(nums, center + 1, right);
merge(nums, left, center, right);
}
}
private static void merge(int[] nums, int left, int center, int right) {
int[] tmpArray = new int[right - left + 1];
int leftIndex = left; //左数组第一个元素的索引
int rightIndex = center + 1; //右数组第一个元素索引
int tmpIndex = 0;
// 把较小的数先移到新数组中
while (leftIndex <= center && rightIndex <= right) {
if (nums[leftIndex] <= nums[rightIndex]) {
tmpArray[tmpIndex++] = nums[leftIndex++];
}
else {
tmpArray[tmpIndex++] = nums[rightIndex++];
}
}
// 把左边剩余的数移入数组
while (leftIndex <= center) {
tmpArray[tmpIndex++] = nums[leftIndex++];
}
// 把右边剩余的数移入数组
while (rightIndex <= right) {
tmpArray[tmpIndex++] = nums[rightIndex++];
}
System.arraycopy(tmpArray, 0, nums, left, tmpArray.length);
}
}