//使用二维数组打印一个10行的杨辉三角 //1.第一行有1个元素,第n行有n个元素 //2.每一行的第一个元素和最后一个元素都是1 //3.从第三行开始,对于非第一个元素和最后一个元素的元素,满足: //yanghui[i][j]=yanghui[i-1][j-1]+yanghui[i-1][j]; public class YangHuiTest { public static void main(String[] args) { //1.声明并初始化二维数组 int[][] yanghui=new int[10][]; //2.给数组赋值 for (int i = 0; i < yanghui.length; i++) { yanghui[i]=new int[i+1]; //每一行有多少个元素 //2.1给首末元素赋值 yanghui[i][0]=1; yanghui[i][i]=1; //2.2给每行非首末元素赋值 if(i>1){ for (int j = 1; j <yanghui[i].length-1 ; j++) { yanghui[i][j]=yanghui[i-1][j-1]+yanghui[i-1][j]; } } } //3.遍历二维数组 for (int i = 0; i < yanghui.length; i++) { for (int j = 0; j < yanghui[i].length; j++) { System.out.print(yanghui[i][j]+" "); } System.out.print("\n"); } } }
//数组的复制 public class Copy { public static void main(String[] args) { //赋值array2等于array1,不能称作数组的复制 int[] array1; int[] array2; array1=new int[]{1,3,4,5,6}; array2=new int[array1.length]; for (int i = 0; i < array2.length; i++) { array2[i]=array1[i]; } for (int i = 0; i < array2.length; i++) { System.out.print(array2[i]+" "); } }
//数组反转 public class Reverse { public static void main(String[] args) { int[] array={1,3,4,5,6,7,4,3}; //数组反转 for (int i = 0,j=array.length-1; i <j ; i++,j--) { int temp=array[i]; array[i]=array[j]; array[j]=temp; } //遍历 for (int i = 0; i < array.length; i++) { System.out.print(array[i]+" "); } } }
//线性查找 public class LinearLook { public static void main(String[] args) { int[] array={1,3,4,5,6,7,4,3}; //线性查找 int dest=8; boolean isFlag=true; for (int i = 0; i < array.length; i++) { if(array[i]==dest){ System.out.println(i); isFlag=false; break; } } if(isFlag){ System.out.println("没有找到"); } } }
public class Binary { public static void main(String[] args) { int[] array1={1,3,43,5,6,8,19,4,9}; //{1,3,4,5,6,8,9,19,43} Arrays.sort(array1); //二分法查找,前提是所要查找的数组必须有序 int dest=43; int head=0;//初始首索引 int end=array1.length-1; boolean isFlag=true; while(head<=end){ int middle=(end+head)/2; if(dest==array1[middle]){ System.out.println("找到了指定元素:"+middle); isFlag=false; break; }else if(dest>array1[middle]){ head=middle+1; }else{ end=middle-1; } } if(isFlag){ System.out.println("没找到"); } } }
十大内部排序算法(主要是前面八种)
关于排序算法数据结构里边的排序算法讲的比较详细!还附有相应的代码
//冒泡排序 public class BubbleSort { public static void main(String[] args) { int[] arr=new int[]{2,3,4,5,6,2,1,9,0,8}; //外层决定循环的次数 for (int i = 0; i < arr.length-1; i++) { //内层决定怎么排序 for (int j = 0; j < arr.length-1-i; j++) { int temp=0; if(arr[j+1]<arr[j]){ temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } }