<menu id="ycqsw"></menu><nav id="ycqsw"><code id="ycqsw"></code></nav>
<dd id="ycqsw"><menu id="ycqsw"></menu></dd>
  • <nav id="ycqsw"></nav>
    <menu id="ycqsw"><strong id="ycqsw"></strong></menu>
    <xmp id="ycqsw"><nav id="ycqsw"></nav>
  • java基礎算法和結構(詳解java常用算法)


    一、分支語句

    流程控制語句對任何一門編程語言都是非常重要的,Java中基于流程控制程序執行的不同步驟和代碼塊。

    1、IF條件

    IF條件語句會根據不同的判斷條件執行不同的語句,if后括號內的條件是否成立關鍵步驟,IF條件的判斷結果必然要是true或false。IF…Else語句則是滿足IF條件,就執行相應代碼塊,否則就執行Elase代碼塊。

    public class Process01 {
        public static void main(String[] args) {
            // 演示:Node01
            if (compare01(40,30)){
                System.out.println("40>30:true");
            } else {
                System.out.println("40>30:false");
            }
            // 演示:Node02
            if (compare01(10,20) && compare01(20,30)){
                System.out.println("條件成立");
            } else {
                System.out.println("條件不成立");
            }
            // 演示:Node03
            if (compare01(20,10) || compare01(20,30)){
                System.out.println("條件成立");
            } else {
                System.out.println("條件不成立");
            }
            // 演示:Node04
            if(compare02(1,1))
                if(compare02(2,2))
                    System.out.println("Running...");
            // 演示:Node05
            if(compare01(1,2))
                if(compare01(5,3)){
                    System.out.println("5>3");
                }
        }
    
        private static boolean compare01 (int num1,int num2){
            System.out.println("判斷:num1="+num1+";num2="+num2);
            return num1 > num2 ;
        }
        private static boolean compare02 (int num1,int num2){
            System.out.println("判斷:num1="+num1+";num2="+num2);
            return num1 == num2 ;
        }
    }

    節點案例,測試結果描述:

    • Node01:如果if條件不成立,則執行else流程或者結束;
    • Node02:邏輯且判斷,任何條件不成立,則直接結束;
    • Node03:邏輯或判斷,任何條件成立,則直接進入分支;
    • Node04:IF的格式,可以去掉{},后續語句會作為分支;
    • Node05:IF語句面試題,不會輸出任何內容,第二個語句作為分支;

    注意:在流程控制語句中必須使用大括號,即使只有一行代碼,避免采用單行的編碼方式,這是基礎規范。在上面的測試節點4和5,代碼看著就感覺扎心。

    2、IF-Else-IF條件

    Else…IF分支語句用于多種情況進行的判斷處理,直到分支判斷條件成功,執行分支模塊代碼,如果沒有else條件,可以所有分支都不滿足,直接結束。

    public class Process02 {
        public static void main(String[] args) {
            elseIf(11) ;
            elseIf(9) ;
            elseIf(5);
        }
    
        private static void elseIf (Integer num){
            if (num > 10){
                System.out.println("num > 10");
            } else if (num > 7){
                System.out.println("num > 7");
            } else if (num > 4){
                System.out.println("num > 4");
            } else {
                System.out.println("num < 4");
            }
        }
    }

    注意:根據條件逐個判斷,直到找到第一個滿足的條件,不會再繼續往下面的判斷執行,分支語句執行完畢就會退出當前的else…if流程。超過3層的的邏輯判斷代碼可以使用衛語句、策略模式、狀態模式等來實現。

    3、Switch條件

    流程描述:switch語句先獲取表達式的值,判斷表達式的值與case語句后的常量值是否相同,匹配成功則執行該case后的代碼塊,直到遇到break語句后終止,如果缺失break打斷,則繼續匹配下一case常量,直到遇到break為止。如果條件全不匹配,則執行default后面的語句。default語句可選,如果不存在default語句,同一個switch語句,case的常量值必須互不相同。

    public class Process03 {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.print("What day is it today:");
            String value = scan.next();
            weekInfo(value);
        }
    
        private static void weekInfo (String value){
            switch (value) {
                case "Monday":
                    System.out.println("Monday");
                    break;
                case "Tuesday":
                    System.out.println("Tuesday");
                    break;
                case "Wednesday":
                    System.out.println("Wednesday");
                    break;
                case "Thursday":
                    System.out.println("Thursday");
                    break;
                case "Friday":
                    System.out.println("Friday");
                    break;
                case "Saturday":
                    System.out.println("Saturday");
                    break;
                case "Sunday":
                    System.out.println("Sunday");
                    break;
                default:
                    System.out.println("Matching failure");
                    break;
            }
        }
    }

    注意:從JDK1.7之后,switch支持對String字符串的匹配。

    二、循環語句

    循環語句就是在滿足特定條件的情況下,反復執行同個操作。循環語句包括:for循環、while循環、do···while循環。

    1、For循環

    Java開發中最有用的循環方式,也是諸多算法中的基礎控制語句,在常見的很多算法編碼實現中,都需要借助for循環方式。

    public class Process04 {
        public static void main(String[] args) {
            // Node01
            int sum = 0;
            for(int i=1; i<=100; i++) {
                sum += i;
            }
            System.out.println(sum);
    
            // Node02
            String[] nameArr = {"Java","C++","C#"} ;
            for (String name:nameArr){
                System.out.println("name="+name);
            }
    
            // Node03
            // 輸出 i = 13
            int i = 0;
            for (i++; i++ < 10; i++);
            System.out.println(++i);
    
            // 輸出:j=3 6 9
            int j = 0;
            for (j++; j++ < 10; j++){
                System.out.println(++j);
            }
        }
    }

    節點案例,測試結果描述:

    • Node01:for循環作為計算中的常用方式;
    • Node02:foreach遍歷模式,簡化循環操作,也可以改寫為for語句;
    • Node03:循環for語句的基礎執行機制,兩道面試常見題;

    注意:越是基礎的東西,學起來越難,for語句作為很多算法實現的基礎控制,理解起來相當的繞。

    2、While循環

    while循環語句首先判斷條件是否成立,成立才執行循環體;

    do···while循環語句先執行一次循環體,然后判斷條件是否成立,所以do···while至少會執行一次;

    public class Process05 {
        public static void main(String[] args) {
            int num1 = 1;
            int num2 = 1;
    
            // while循環
            while(num1 <= 3) {
                System.out.println("num1 == " + num1);
                num1++;
            }
    
            // do...while循環
            do {
                System.out.println("num2 == " + num2);
                num2++;
            } while(num2 <= 3);
        }
    }

    注意:while循環在實際的開發中,因為極其容易導致死循環,所以使用并不多。

    三、流程中斷

    Java中有三種流程中斷語句,關鍵字分別為break、continue、return語句。

    1、Return語句

    Java中最常用的流程控制關鍵字,當執行return語句后,從該方法返回,返回到調用該方法的業務流程中。

    public class Process06 {
        public static void main(String[] args) {
            System.out.println(getNum1());
            System.out.println(getNum2());
        }
        public static int getNum1 (){
            int a =100;
            try{
                return a+1;   // 這里是運算邏輯,非賦值
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                return a;
            }
        }
        public static int getNum2 (){
            int a =100;
            try{
                return a++;   //  a++ -> a=a+1 此時a的值改變
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                return a;
            }
        }
    }

    return 常在位置

    • return語句只在方法最后出現一次。
    • return語句僅在try和catch里面都出現。
    • return語句僅在try和方法最后都出現。
    • return語句僅在catch和方法的最后都出現。

    2、Break語句

    break中斷語句常用在for、while、do···while循環中,用于退出當前整個循環流程,非當前這一次循環。

    public class Process07 {
        public static void main(String[] args) {
            for (int i = 1 ; i < 3 ; i++){
                if (i == 2){
                    break ;
                }
                System.out.println("i = " + i);
            }
        }
    }

    3、Continue語句

    Continue中斷語句常用在for、while、do···while循環中,用于退出當前這一次循環,進入下一次循環。

    public class Process08 {
        public static void main(String[] args) {
            for (int i = 1 ; i < 3 ; i++){
                if (i == 1){
                    continue ;
                }
                System.out.println("i = " + i);
            }
        }
    }

    四、應用場景

    1、冒泡排序算法

    public class Process09 {
        public static void main(String[] args) {
            int[] score = {9,8,7,6,5} ;
            // 排序次數:最多 length - 1 次
            for (int i = 0 ; i < score.length -1 ; i ++){
                // 當前排序的集合區間,排序完一個數據就放棄一個
                for (int j = 0 ; j < score.length - i - 1 ; j++){
                    // 冒泡排序:把結果大的向后扔
                    if (score[j] > score[j+1]){
                        int temp = score[j] ;
                        score[j] = score[j+1] ;
                        score[j+1] = temp ;
                    }
                }
            }
            // 輸出排序后的結果集
            for (int i = 0 ; i < score.length ; i++){
                System.out.print(score[i]);
            }
        }
    }

    2、排列組合算法

    有1、2、3、4個數字,能組成多少個互不相同且無重復數字的三位數?都是多少?

    public class Process10 {
        public static void main(String[] args) {
            arrange() ;
        }
        public static void arrange (){
            int i=0; // 百位數
            int j=0; // 十位數
            int k=0; // 個位數
            int t=0; // 計數器
            for (i = 1 ; i <= 4 ; i++){
                for (j = 1 ; j <= 4 ; j++){
                    for (k = 1 ; k <=4 ; k++){
                        if (i != j && j != k && k != i){
                            t += 1 ;
                            System.out.print(i*100+j*10+k+"--");
                        }
                    }
                }
            }
            System.out.println();
            System.out.println("t="+t);
        }
    }

    3、遞歸常見算法

    基于遞歸思想的各種計算方法實現。

    public class Process11 {
        public static void main(String[] args) {
            System.out.println(getSumOne(100));
            System.out.println(getSumTwo(30));
            System.out.println(getSumThree(5));
        }
        /**
         * 使用遞歸的方式計算1+2+...+100
         */
        public static int getSumOne (int i){ // 傳入100
            int sum ;
            if (i == 1){
                return 1 ;
            }
            else {
                sum = i + getSumOne(i - 1) ;
            }
            return sum ;
        }
        /**
         * 一列數的規則如下: 1、1、2、3、5、8、13、21、34...
         * 求第30位數是多少, 用遞歸算法實現
         */
        public static int getSumTwo (int i){ // 傳入第幾位數下標
            if (i <= 0){
                return 0 ;
            } else if (i == 1 || i == 2){ // 處理前面2位的1,1
                return 1 ;
            } else { // 當前位數是前兩位之和
                return getSumTwo(i - 1) + getSumTwo(i - 2) ;
            }
        }
        /**
         * 1*2*3*...*100 遞歸計算階乘
         */
        public static int getSumThree (int i){
            if (i == 1){
                return i ;
            } else {
                return i * getSumThree (i - 1) ;
            }
        }
    }

    版權聲明:本文內容由互聯網用戶自發貢獻,該文觀點僅代表作者本人。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如發現本站有涉嫌抄襲侵權/違法違規的內容, 請發送郵件至 舉報,一經查實,本站將立刻刪除。

    發表評論

    登錄后才能評論
    国产精品区一区二区免费