BubbleSort

Bubble sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

 1 /*
 2  * Best     Average    Worst     Memory   Stable
 3  *  n         n^2       n^2        1       Yes
 4 */
 5 public class BubbleSort {
 6 
 7     public static void sort(int[] a){
 8         int temp=0;
 9         boolean flag=true;
10         for(int i=a.length-1;i>0 && flag;i--){
11             flag=false;
12             for(int j=0;j<i;j++){
13                 if(a[j+1]<a[j]){
14                     flag=true;
15                     temp=a[j];
16                     a[j]=a[j+1];
17                     a[j+1]=temp;
18                 }
19             }
20         }
21     }
22     
23     public static void printArray(int[] a){
24         for(int i = 0;i < a.length;i++){
25             System.out.print(a[i]+" ");
26         }
27     }
28     
29     public static void main(String[] args) {
30         // TODO Auto-generated method stub
31         int[] a=new int[]{2, 1, 5, 4, 9, 8, 6, 7, 10, 3};
32         sort(a);
33         printArray(a);
34     }
35 
36 }

 

posted on 2013-03-29 16:19  melotang  阅读(152)  评论(0)    收藏  举报