Java-冒泡排序、选择排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//冒泡排序:比较相邻的元素,如果前一个比后一个大,交换O(n2)
public void bubbleSort(){
 
    int[] arr={3,6,34,12,56,37,54,89,23};
 
    for (int i=0;i<arr.length;i++){
        for (int j=i+1; j<arr.length;j++){
 
            if(arr[i]>arr[j]){
                int temp= arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
 
    for (int i=0;i<arr.length;i++){
        System.out.print(arr[i]+",");
    }
     
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    //选择排序:每次选择最小的,一次放在1,2,3等位置依次交换O(n2)
    public void SelectionSort(){
 
        int[] arr={3,6,34,12,56,37,54,89,23};
        int flag=0;
        int temp=0;
 
        for (int i=0;i<arr.length;i++){
            temp=arr[i];
            flag=i;
            for (int j=i+1; j<arr.length;j++){
                if(arr[j]<temp){
                    temp=arr[j];
                    flag=j;
                }
 
            }
<br>          //把最小的数据交换
            if (flag!=i){
                arr[flag]=arr[i];
                arr[i]=temp;
            }
<br>           //每排序一次,输出一次
            for (int a=0;a<arr.length;a++){
                System.out.print(arr[a]+",");
            }
            System.out.println();
        }
 
    }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//插入排序<br>   public void insertSort() {
 
        int[] arr = {3, 2, 34, 12, 56, 37, 54, 89, 23};
 
        for (int i=1 ;i<arr.length;i++){
 
            int temp=arr[i];
 
            int j=i-1;
            for (;j>=0;j--){
 
                if(arr[j]>temp){
                    arr[j+1]=arr[j];
                }
                else{break;}
 
                }
            if(arr[i]!=temp){
                arr[j+1]=temp;
            }
 
            for (int a=0;a<arr.length;a++){
                System.out.print(arr[a]+",");
            }
            System.out.println();
 
        }
    }

  

posted @   测试一枚  阅读(168)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示