冒泡排序(转载)

  1. public class TestBubbleSort {  
  2.   
  3.     public static void bubbleSortFirst(int[] data){  
  4.         for (int i = 1; i < data.length; i++) {  
  5.             int temp;  
  6.             for (int j = 0; j < data.length-i; j++) {  
  7.                 if(data[j]>data[j+1]){  
  8.                     temp = data[j];  
  9.                     data[j] = data[j+1];  
  10.                     data[j+1] = temp;  
  11.                 }  
  12.             }  
  13.         }  
  14.     }  
  15.       
  16.     public static void bubbleSortSecond(int[] data){  
  17.         for (int i = data.length-1;i>0;i--) {  
  18.             int temp;  
  19.             boolean isExchanged = false;  
  20.             for (int j = 0; j < i; j++) {  
  21.                 if(data[j]>data[j+1]){  
  22.                     temp = data[j];  
  23.                     data[j] = data[j+1];  
  24.                     data[j+1] = temp;  
  25.                     isExchanged = true;  
  26.                 }  
  27.             }  
  28.             if(!isExchanged){  
  29.                 return;  
  30.             }  
  31.         }  
  32.     }  
  33.       
  34.     public static void main(String[] args) {  
  35.         int[] a = {2,34,1,56,28,98};  
  36. //      bubbleSortFirst(a);  
  37.         bubbleSortSecond(a);  
  38.         for (int i = 0; i < a.length; i++) {  
  39.             System.out.print(a[i]+"\t");  
  40.         }  
  41.     }  
  42. }  
posted @ 2011-12-09 16:30  agile_work  阅读(96)  评论(0)    收藏  举报