方法重载
斐波拉契数列问题 使用重载思想解决
public static int method(int n){if (n == 2 ){return 1 ;}return (n-1)*2+method(n-1);}public static int f(int n){if (n == 1){return 1;}if (n == 2){return 2;}return f(n-1)+f(n-2);}
快速排序
思维很简单,类似二分查找利用for循环逼近中间值,但实际计算时比较复杂
二分查找public static void main(String[] args) {Scanner scan = new Scanner(System.in);int arr[] = {1,5,9,45,88,102,555};int max = arr.length-1;int min = 0;int mid = (max+min)/2;int num = scan.nextInt();while (num !=arr[mid]){if (num > arr[mid]){min = mid+1;mid = (max+min)/2;}else if(num < arr[mid]){max = mid -1;mid = (max+min)/2;}if (min > max){break;}}if (min <= max){System.out.println("找到了"+arr[mid]);}else {System.out.println(-1);}}
public class QuickSort {public static void main(String[] args) {int[] arr = {6,3,12,2,15,19,7,3,1};quickSort(arr.length-1,0,arr);System.out.println(Arrays.toString(arr));}public static void quickSort(int right,int left,int arr[]){if ( left > right ){return;}int j = right;int i = left;int base =arr[left] ; //定义一个基准数while(i != j){//在左表与右标遍历完整个数组时跳出循环while (arr[j] >= base && i < j){//在右侧找一个小于基准的数,然后跳出循环 得到jj--;//往左遍历}while (arr[i] <= base && j > i){//在左侧直到找到一个大于基准的数,然后跳出循环 得到ii++;//往右遍历}//交换对应值int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}//交换基准值 交换 ij相遇值和基准值所在位置
// int temp1 = arr[i];
// arr[i] = base;
// base = temp1;arr[left] = arr[i]; //把相遇位置上的元素赋值给 原来基准数所在位置arr[i] = base; // 把基准数赋值给相遇位置quickSort(i-1,left,arr);//递归左半边quickSort(right,j+1,arr);//递归左半边
二维数组for循环打印杨辉三角
打印杨辉三角类似 打印 直角三角形 菱形 99乘法表
public static void main(String[] args) {Scanner scan = new Scanner(System.in);System.out.println("请输入行数:");int row = scan.nextInt();//定义一个二维数组用于存储杨辉三角int[][] arr = new int[row][];//向二维数组中填充值for (int i = 0; i < arr.length; i++) {//获取到杨辉三角的每一行//因为每一行都是null,需要赋值arr[i] = new int[i + 1];//遍历arr[i]填充元素for (int j = 0; j < arr[i].length; j++) {if(j==0 || j==i){arr[i][j] =1;}else{arr[i][j] = arr[i-1][j-1] + arr[i-1][j];}//System.out.print(arr[i][j] +"\t");}// System.out.println();}//打印杨辉三角for (int i = 0; i < arr.length; i++) {//打印空格for (int j = 0; j < arr.length-i-1; j++) {System.out.print(" "); //2个空格}//打印杨辉三角for (int j = 0; j <=i; j++) {System.out.print(arr[i][j]+" "); //3个空格}System.out.println();}}