java算法:冒泡排序

java算法:冒泡排序

冒泡排序:不断遍历文件,交换倒序的相邻元素,直到文件排好顺序。冒泡排序的主要优点是容易实现,冒泡排序通常会比选择排序、插入排序慢。

如,对EXAMPLE 字母进行排序:
 E   X   A   M   P   L   E   .开始
[A]  E   X  [E]  M   P   L   .E移到了A之后,A移到了最前面
 A   E  [E]  X   L   M   P   .L移到了E之后,E移到了X前面
 A   E   E  [L]  X   M   P   .L移到了X前面
 A   E   E   L  [M]  X   P   ...
 A   E   E   L   M  [P]  X   
 A   E   E   L   M   P  [X]

Prettyprint java代码 复制代码
  1. public class Bubble {   
  2.   
  3.     public static void main(String[] args) {   
  4.         int n = 20;   
  5.         MyItem [] a = new MyItem[n];   
  6.         for (int i = 0; i < n; i++) {   
  7.             a[i] = new MyItem();   
  8.             a[i].rand();   
  9.         }   
  10.            
  11.         for (int i = 0; i < n; i++) {   
  12.             System.out.print(a[i] + " ");   
  13.         }   
  14.            
  15.         bubble(a, 0, n);   
  16.         System.out.println("");   
  17.         print(a, n);   
  18.     }   
  19.        
  20.     private static void print(MyItem a [], int n){   
  21.         for (int i = 0; i < n; i++) {   
  22.             System.out.print(a[i] + " ");   
  23.         }   
  24.     }   
  25.        
  26.     public static void bubble(MyItem [] a, int l, int r){   
  27.         for (int i = l; i < r; i++) {   
  28.             for (int j = r - 1; j > i; j--) {   
  29.                 compExch(a, j - 1, j);   
  30.             }   
  31.         }   
  32.     }   
  33.        
  34.     public static boolean less(Item v, Item w){   
  35.         return v.less(w);   
  36.     }   
  37.        
  38.     public static void exch(Item [] a, int i, int j){   
  39.         Item t = a[i];   
  40.         a[i] = a[j];   
  41.         a[j] = t;   
  42.     }   
  43.        
  44.     public static void compExch(Item [] a, int i, int j){   
  45.         if(less(a[j],a[i])){   
  46.             exch(a, i, j);   
  47.         }   
  48.     }   
  49. }  
原文地址:https://www.cnblogs.com/wuyida/p/6301140.html