排序

比较3种排序交换次数:

public class TEst {
    public static void main(String[] args) {
        int[] arr={4,3,2,1,7,90,45,56,34,23,67,67,34,23,13,23};
        int[] arr1={4,3,2,1,7,90,45,56,34,23,67,67,34,23,13,23};
        int[] arr2={4,3,2,1,7,90,45,56,34,23,67,67,34,23,13,23};
        int count=0;
        int count1=0;
        int count2=0;
        for(int i=0;i<arr.length-1;i++){
            for (int j = i+1; j < arr.length; j++) {
                int temp;
                if(arr[i]>arr[j]){
                    temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                    count++;
//                    System.out.println(Arrays.toString(arr));
                }
            }
        }
        for(int i=0;i<arr1.length-1;i++){
            for(int j=0;j<arr1.length-i-1;j++){
                int temp;
                if(arr1[j]>arr1[j+1]){
                    temp=arr1[j+1];
                    arr1[j+1]=arr1[j];
                    arr1[j]=temp;
                    count1++;
//                    System.out.println(Arrays.toString(arr1));
                }
            }
        }
        for(int i=0;i<arr2.length-1;i++){
            int index=i;
            int temp;
            for(int j=i+1;j<arr2.length;j++){
                if(arr2[index]>arr2[j]){
                    index=j;
                }
            }
            temp=arr2[index];
            arr2[index]=arr2[i];
            arr2[i]=temp;
            count2++;
        }
        System.out.println(Arrays.toString(arr));
        System.out.println("第一种排序移动次数:"+count);
        System.out.println(Arrays.toString(arr1));
        System.out.println("冒泡排序移动次数:"+count1);
        System.out.println(Arrays.toString(arr2));
        System.out.println("选择排序移动次数:"+count2);
    }
}
Out:

[1, 2, 3, 4, 7, 13, 23, 23, 23, 34, 34, 45, 56, 67, 67, 90]
第一种排序移动次数:37
[1, 2, 3, 4, 7, 13, 23, 23, 23, 34, 34, 45, 56, 67, 67, 90]
冒泡排序移动次数:45
[1, 2, 3, 4, 7, 13, 23, 23, 23, 34, 34, 45, 56, 67, 67, 90]
选择排序移动次数:15



 

posted @ 2019-05-12 19:50  笔记Next  阅读(116)  评论(0编辑  收藏  举报