插入排序
/** * 插入排序 * * @throws Exception */ @Test public void tes1() throws Exception { int[] a = { 2, 6, 1, 8, 3, 9, 5 }; for (int i = 1; i < a.length; i++) { System.out.print(i+" :"); for (int j = i; j > 0; j--) { System.out.print(j +" "); if (a[j] > a[j - 1]) { // break; } else { int b = a[j]; a[j] = a[j - 1]; a[j-1] = b; } } System.out.println(); } for (int i : a) { System.out.print(i+" "); } }
计算和 ------------------------ public int he(int n) throws Exception { if (n == 1) { return 1; }else{ return (he(n-1))+(n); } } 斐波拉契数列 --------------------------- public static int fb(int n) { // 1 1 2 3 5 8 if (n<3) { return 1; }else{ return fb(n-1)+fb(n-2); } }
== 选择排序 int[] a = { 2, 6, 1, 8, 3, 9, 5 }; for (int i = 0; i < a.length; i++) { System.out.print(i+" :"); for (int j = i + 1; j < a.length; j++) { System.out.print(j+" "); if (a[i] > a[j]) { int b = a[j]; a[j] = a[i]; a[i] = b; } } System.out.println(); } for (int i : a) { System.out.print (i+" "); }
冒泡排序 === int[] a = { 2, 6, 1, 8, 3, 9, 5 }; for (int i = 1; i < a.length; i++) { System.out.print(i + " :"); for (int j = a.length-1; j >=i; j--) { if (a[j]<a[j-1]) { int b = a[j]; a[j] = a[j-1]; a[j-1] = b; } System.out.print(j + " "); } System.out.println(); } for (int i : a) { System.out.print(i + " "); }
文件目录 递归: ===== public static void tes5(File file) throws Exception { File[] listifle = file.listFiles(); for (File file2 : listifle) { if (file2.isDirectory()) { System.out.println(file2.getPath()); tes5(file2); } else { System.out.println(file2.getName()); } } }
二分法查找: 适合有序数组 ------- //只适合有序数组 public static void foldfind(int[] a,int left,int right,int ren){ //求mid int mid=(left+right)/2; if(a[mid]==ren){ System.out.println(ren+"找到,下标是"+mid); }else if(mid<right&&a[mid]<ren){//到mid右边找,必须右边要有数 foldfind(a, mid+1, right, ren); }else if(left<mid&&a[mid]>ren){//到左边找 foldfind(a, left, mid-1, ren); }else{ System.out.println("查无此人"); } }
快速排序: =============== public static void fastsort(int[] a, int left, int right) { // 1、取参考值mid int mid = a[left]; // 2、设立两个指针 int i = left, j = right; while (i < j) { // 3、从j开始向前找一个小于mid的数与其交换 while (i < j && a[j] >= mid) { j--; } if (i < j) {// 表示找着一个小于mid数 int b = a[i]; a[i] = a[j]; a[j] = b; } // 4、从i开始向后找一个大于mid的数与其交换 while (i < j && a[i] < mid) { i++; } if (i < j) {// 表示找着一个大于mid数 int b = a[i]; a[i] = a[j]; a[j] = b; } } // i,j相遇,以mid为中心,左边全小,右边全大 // 左边有数,左边快速排序 if (left < i) { fastsort(a, left, i - 1); } // 右边有数,右边快速排序 if (right > j) { fastsort(a, j + 1, right); } }