排序

1.冒泡排序

 1 package myTest;
 2 
 3 import java.util.Arrays;
 4 
 5 public class maopao {
 6     public static int[] getArray(int[] arr){
 7         int temp;
 8         int count=0;//比较次数
 9         for(int i=0;i<arr.length;i++){
10             for(int j=0;j<arr.length-1-i;j++){//注意比较右侧无需比较
11                 System.out.println("第"+ ++count+"次比较");
12                 System.out.println(Arrays.toString(arr));
13                 if(arr[j]>arr[j+1]){
14                     temp=arr[j];
15                     arr[j]=arr[j+1];
16                     arr[j+1]=temp;
17                 }
18             }
19         }
20         return arr;
21     }
22     public static int[] getArray2(int[] arr){
23         int temp;
24         int count=0;
25         for(int i=0;i<arr.length-1;i++){
26             for(int j=arr.length-1;j>i;j--){
27                 count++;
28                 if(arr[j]<arr[j-1]){
29                     temp=arr[j];
30                     arr[j]=arr[j-1];
31                     arr[j-1]=temp;
32                 }
33             }
34         }
35         System.out.println("比较次数"+count);
36         return arr;
37     }
38     public static void main(String[] args) {
39         int[] arr={7,6,5,3,2};
40         getArray2(arr);
41         System.out.println(Arrays.toString(arr));
42     }
43 }
原文地址:https://www.cnblogs.com/mryangbo/p/8258069.html