• <noscript id="ecgc0"><kbd id="ecgc0"></kbd></noscript>
    <menu id="ecgc0"></menu>
  • <tt id="ecgc0"></tt>

    教你理解冒泡排序。

    當我們學習計算機編程時,講師總是會拿一些簡單的邏輯題給我們練習,下面的內容帶你理解簡單的程序,冒號排序。

    操作方法

    • 01

      首先是弄清楚原理:相鄰的兩個數進行比較,按照從小到大或者從大到小的順序進行交換,就這樣一次循環最大或者最小的數字就被拍到最后一位,然后再從頭開始進行兩兩比較交換,直到結束。下面通過例子分步驟講解(按從小到大的順序排列)。

    • 02

      定義一個數組{5 ,6, 1,4 ,3}
      第一次循環得到結果為:5 - 1 - 4 -3 -6

    • 03

      第二次循環得到結果為:1 - 4 - 3 -5 -6

    • 04

      如此類推最后得到的結果:1 -3 -4 -5 -6
      下面進入代碼:
      定義一個數組儲存數據,順便輸出一下,用for循環,length獲取數組長度

    • 05

      接下來就是最重要的邏輯處理
      這里就是交換的過程 ,利用雙層for循環實現相鄰兩個數之間的交換
      定義一個temp用于交換
      直接看代碼。

    • 06

      當上面的代碼執行完成那么順序也就排好了,在利用for循環輸出

    • 07

      下面是完整代碼:

      public static void main(String[] args) {

      //定義一個數組,存儲數據
      int[] x = {5, 6, 1, 4, 3, 8};

      System.out.print("排序前的順序:");

      //循環輸出
      for (int i = 0; i < x.length; i++)
      {
      System.out.print(x[i]+"\t");
      }

      //排序的邏輯處理
      for (int i = 0; i < x.length; i++) {
      for (int j = i; j < x.length; j++) {
      if (x[i] > x[j]) {
      int temp = x[i];
      x[i] = x[j];
      x[j] = temp;
      }
      }
      }

      System.out.println();
      System.out.print("排序后的順序:");
      for (int i = 0; i < x.length; i++)
      {
      System.out.print(x[i]+"\t");
      }
      }

    • 08

      最后的排序結果:

    • End
    • 發表于 2017-09-02 00:00
    • 閱讀 ( 1065 )
    • 分類:電腦網絡

    你可能感興趣的文章

    相關問題

    0 條評論

    請先 登錄 后評論
    聯系我們:uytrv@hotmail.com 問答工具
  • <noscript id="ecgc0"><kbd id="ecgc0"></kbd></noscript>
    <menu id="ecgc0"></menu>
  • <tt id="ecgc0"></tt>
    久久久久精品国产麻豆