[Java] 冒泡算法 - 亲手敲的供参考 →→→→→进入此内容的聊天室

来自 , 2019-07-06, 写在 Java, 查看 104 次.
URL http://www.code666.cn/view/e2a2dcc3
  1. package bubbleSort;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class TestBubbleSort {
  6.  
  7.         public static void main(String[] args) {
  8.                 int[] arr = new int[] { 9, 8, 7, 6, 5, 4, 2, 1 };
  9.                 System.out.println("The unsorted array is                          : "
  10.                                 + Arrays.toString(arr));
  11.                 System.out.println("The sorted array with bubble sort algorithm is : "
  12.                                 + Arrays.toString(BubbleSortImpl.bubbleSort(arr)));
  13.         }
  14. }
  15.  
  16. public class BubbleSortImpl {
  17.    
  18.         //bubble sort
  19.         public static int[] bubbleSort(int[] arr) {
  20.                 int len = arr.length;
  21.                 int temp = Integer.MIN_VALUE;
  22.  
  23.                 for (int i = 0; i < len - 1; i++) {
  24.                         for (int j = 0; j < len - 1 - i; j++) {
  25.                                 if (arr[j + 1] < arr[j]) {
  26.                                         temp = arr[j];
  27.                                         arr[j] = arr[j + 1];
  28.                                         arr[j + 1] = temp;
  29.                                 }
  30.                         }
  31.                 }
  32.                 return arr;
  33.         }
  34. }
  35.  
  36.  
  37. /*运行结果:
  38. The unsorted array is                                       : [9, 8, 7, 6, 5, 4, 2, 1]
  39. The sorted array with bubble sort algorithm is : [1, 2, 4, 5, 6, 7, 8, 9]
  40. */
  41.  
  42.  
  43.  

回复 "冒泡算法 - 亲手敲的供参考"

这儿你可以回复上面这条便签

captcha