1. 程式人生 > >JavaSE程式設計題目~2

JavaSE程式設計題目~2

1. 使用for迴圈列印乘法口訣表
public class Test {
    public static void main(String[] args) {
        for (int i=1; i<10; i++){
            for (int j=1; j<=i; j++) {	     // 重點關注第二個迴圈條件
                System.out.println(i+"*"+j+"="+(i*j));
            }
        }
    }
}
2. 遞迴實現20!
public class Test {
    public static long f(int n ){
        if(n == 1){		// 明確的遞迴終止條件
            return 1;		// 簡單場景
        }
        return n*f(n-1);		// 相同重複邏輯,縮小問題的規模
    }
    public static void main(String[] args) {
        System.out.println(f(20) );
    }
}
3. 使用遞迴實現快速排序(Java實現)
public class Test {
    public static int QuickSort(int list[], int low, int high) {
        int temp = list[low];
        while (low < high) {
            while (low < high && temp <= list[high])
                --high;
            list[low] = list[high];
            while (low < high && temp >= list[low])
                ++low;
            list[high] = list[low];
        }
        list[low] = temp;
        return low;
    }
    //遞迴排序
    public static void quickSort(int list[], int low, int high) {
        if (low < high) {
            int mid = QuickSort(list, low, high);
            quickSort(list, low, mid - 1);
            quickSort(list, mid + 1, high);
        }
    }
    
    public static void main(String[] args) {
        int[] list = new int[]{11, 25, 7, 88, 6, 25, 66, 33, 1, 520, 366};
        QuickSort(list, 0, list.length - 1);
        for (int i = 0; i < list.length; i++) {
            System.out.println(list[i]);
        }
    }
}
4. 使用陣列靜態初始化方式初始化一個大小為10的整型陣列並輸出。
public class Test{
    public static void main(String[] args) {
        int[] arr = {1,2,5,33,2,3,1,32,45,7};
        System.out.println(arr);
    }
}