Java代码Demo——杨辉三角、冒泡排序、二分查找和数组反转

杨辉三角

/**
  * 杨辉三角:
  *                                  1
  *                              1     1
  *                           1     2     1
  *                        1     3     3     1
  *                     1     4     6     4     1
  *                  1     5    10    10     5     1
  *               1     6    15    20    15     6     1
  *            1     7    21    35    35    21     7     1
  *         1     8    28    56    70    56    28     8     1
  *      1     9    36    84   126   126    84    36     9     1
  *  除两边的数以外,任何一个数为上两顶数之和。例如:第3行的2为上顶的1+1
  *  即:arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
  */
public static void yangHui() {
    //定义二维数组
    int[][] arr = new int[10][];
    for (int i = 0; i < arr.length; i++) {
        //数组初始化
        arr[i] = new int[i+1];
        //两边数都是1
        arr[i][0] = arr[i][i] = 1;
        for (int j = 1; j < i; j++) {
            //其他数为上两项数之和
            arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
        }
    }
    //打印三角
    for (int i = 0; i < arr.length; i++) {
        //空格三角
        for (int j = arr.length; j > i ; j--) {
            System.out.print(" ");
        }
        //杨辉三角
        for (int j = 0; j < arr[i].length; j++) {
            System.out.print(" " + arr[i][j]);
        }
        System.out.println();
    }

}

冒泡排序

public static void sort() {
    int[] arr = new int[]{3,-1,0,1,10,7,8,4,-5,9};
    for (int i = 0; i < arr.length-1; i++) {
        for (int j = 0; j < arr.length-1-i; j++) {
            int temp = arr[j];
            if (arr[j] > arr[j+1]) {
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }

    for (int i : arr) {
        System.out.print(i + " ");
    }
}

二分法查找

/**
  * 二分法查找:一定要是有序的数组
  */
public static void test() {
    int temp = 10;
    boolean isFlag = false;
    //有序的数组
    int[] arr = new int[]{3, 5, 10, 17, 69, 200, 888};
    int head = 0;
    int end = arr.length - 1;
    while (head <= end) {
        int middle = (head + end) / 2;
        if (temp == arr[middle]) {
            System.out.println(temp+"的下标为:"+middle);
            isFlag = true;
            break;
        } else if (temp > arr[middle]) {
            head = middle + 1;
        } else {
            end = middle - 1;
        }
    }
    if (!isFlag) {
        System.out.println("抱歉,"+temp+"没有找到");
    }
}

数组反转

/**
  * 数组反转
  */
public static void reversal() {
    String[] names = new String[]{"aa", "bb", "cc", "dd", "gg", "hh", "ii", "jj", "ee"};
    //方式一
    for (int i = 0, j = names.length-1; i < j; i++, j--) {
        String temp = names[i];
        names[i] = names[j];
        names[j] = temp;
    }
    //方式二
    for (int i = 0; i < names.length / 2; i++) {
        String temp = names[i];
        names[i] = names[names.length-1-i];
        names[names.length-1-i] = temp;
    }
    //遍历
    for (String name : names) {
        System.out.print(name + " ");
    }
}

你可能感兴趣的:(代码Demo,java,开发语言)