看故事,學排序

  • 2019 年 12 月 10 日
  • 筆記

來源:I

在面試的過程中,有的面試官也會問到這個排序。今天我們看一個故事來感受一下冒泡排序的過程。

趣談編程註:從上面的圖可以看到,冒泡排序是從1號座位(最左邊)把兩個相鄰的人進行比較,選出實力強的(也可以選擇弱的),

讓強者佔據右邊的位置,然後再將強者(也就是2號座位)的人和他的右邊(3號座位)的人進行比較,就這樣一直讓強者向右冒出(移動)。

一輪排序完,最右邊就是最強的了。

趣談編程註:由於第一輪已經確定5號座位(最右邊)是最強的了,所以5號座位的人不參與第二輪排序。

冒泡排序程式碼實現(java)

如下

/**   * @Version: 1.0   * @Description: 冒泡排序   */    import com.jiajia.ArrayUtil.*;  // 按包名導入    public class BubbleSortMain {        public static void main(String[] args) {          int[] arr = {2,5,1,3,8,5,7,4,3};          bubbleSort(arr);            ArrayUtil.print(arr);        }        /**       * 冒泡排序       * @param arr       */      private static void bubbleSort(int[] arr) {          for (int i = 0; i < arr.length; i++) {              for (int j = 0; j < arr.length - i -1; j++) {                  if (arr[j] > arr[j + 1]) {                      int temp = arr[j];                      arr[j] = arr[j + 1];                      arr[j + 1] = temp;                  }              }          }      }  }

Tags: