冒泡算法的JAVA实现

 

 1 /**
 2  * @author hanxin
 3  * 标题:冒泡排序算法    
 4  */
 5 public class Sort_Bubble {
 6 
 7     //待排序的数组
 8     public static int[] array={1,4,23,54,2,65,21,123,12,34};
 9     //排序算法 从大到小
10     public static int[] sortDown(int[] array)
11     {
12         
13         for(int i=array.length-1;i>=1;i--)
14         {
15             //当array.length=n时,i=n-1
16             for(int j=0;j<i;j++)
17             {
18                 //当i=n-1时,j=n-2,j+1=n-1;
19                 if(array[j]<array[j+1])
20                 {
21                     int temp;
22                     temp=array[j];
23                     array[j]=array[j+1];
24                     array[j+1]=temp;
25                 }
26             }
27         }
28         return array;
29     }
30     //排序算法 从小到大
31     public static int[] sortUp(int[] array)
32     {
33         for(int i=0;i<array.length-1;i++)
34         {
35             
36             for(int j=array.length-1;j>i;j--)
37             {
38                 if(array[j]<array[j-1])
39                 {
40                     int temp;
41                     temp=array[j];
42                     array[j]=array[j-1];
43                     array[j-1]=temp;
44                 }
45             }
46         }
47         return array;
48     }
49     //排序算法
50     public static int[] sort(int [] array,boolean up)
51     {
52         if(up)
53         {
54             return sortUp(array);
55         }
56         else
57         {
58             return sortDown(array);
59         }
60     }
61 
62     /**
63      * @param args
64      */
65     public static void main(String[] args) {
66         // TODO Auto-generated method stub
67         System.out.println("*********对数组元素进行升序排序*********");
68         int []upsortInt=sort(array,true);//升序排序
69         for(int i=0;i<upsortInt.length;i++)
70         {
71             System.out.println(upsortInt[i]);
72         }
73         System.out.println("*********对数组元素进行降序排序*********");        
74         int []downsortInt=sort(array,false);//降序排序
75         for(int i=0;i<downsortInt.length;i++)
76         {
77             System.out.println(downsortInt[i]);
78         }
79     }
80 }
View Code

 这是今年8月8号写的,今天放上来共享。如果有什么问题,请指出,谢谢^_^。

 

 

小小程序员--一直很安静的我。

posted on 2013-08-23 15:28  一直很安静的我  阅读(125)  评论(0)    收藏  举报

导航