Java_数组的冒泡排序

 1 import java.util.*; //Java定义好的功能
 2 class ArrayOperateDemo2
 3 {
 4     /*
 5     定义一个功能,为了遍历数组中的元素
 6     */
 7     public static void printArray(int[] arr)
 8     {
 9         for (int x=0;x<arr.length ;x++ )
10         {
11             //去除行尾,
12             if (x!=arr.length-1)
13             {
14             System.out.print(arr[x]+",");
15             }
16             else
17                 System.out.println(arr[x]);
18         }
19     }
20 
21     /*
22     定义一个输出功能
23     */
24 
25     public static void sop(String str)
26     {
27         System.out.println(str);
28     }
29     /*
30     定义一个函数,用于排序替换值得操作
31     对数组中的元素未知进行置换
32     swap();
33     */
34     public static void swap(int[] arr,int a,int b)
35     {
36         int temp=arr[a];
37         arr[a]=arr[b];
38         arr[b]=temp
39     }
40 
41         //排序中最快的是希尔排序
42 
43     /*
44     冒泡排序:相邻两个元素比较
45     */
46     public static void bubbleSort(int[] arr)
47     {
48         for (int x=0;x<arr.length-1 ;x++ )
49         {
50             for (y=0;y<arr.length-1-x ;y++ )
51             {
52                 if(arr[y]>arr[y+1])
53                 {
54                     /*int temp =arr[x];
55                     arr[y]=arr[y+1];
56                     arr[y+1]=temp;*/
57                     swap(arr,y,y+1);
58                 }
59             }
60         }
61     }
62 
63     public static void main(String[] args) 
64     {
65         int[] arr={57,23,19,89,66,74};
66         sop("排序前:");
67         printArray(arr);
68 
69         //selectSort(arr);
70         //bubbleSort(arr);
71         Arrays.sort(arr);//java中提供的数组排序方式,开发都用它
72 
73         sop("排序后:");
74         printArray(arr);
75 
76     }
77 
78 
79 }
80 
81 
82  

posted @ 2017-10-31 09:08  BirdieForLove  阅读(369)  评论(0编辑  收藏  举报