您的位置:首页 > 其它

(第3讲)简单排序:冒泡。选择。插入

2016-06-20 12:11 316 查看
首先对这三种简单排序进行比较:

 冒泡选择插入
比较次数N(N-1)/2N(N-1)/2N(N-1)/4
交换次数N^2/4NN(N-1)/4
不变性out右边有序out左边有序(下标小于等于out的项有序)下标小于等于out的项部分有序
1、冒泡

package com.three;

public class myBubble {

    public static void main(String[] args) {

        int[] a= {77,99,44,55, 22, 88,-96 ,11 ,0, 66,33,-5 };

        mybubble2 b = new mybubble2(a);

        b.sort();

    }

}

//冒泡排序

class mybubble2{

    private int[] a;

    public mybubble2(int[] a){

        this.a = a;

    }

    public void sort(){

        for(int i=0;i<a.length;i++){

            

            for(int j = 0;j<a.length-1-i;j++){

                if(a[j]>a[j+1]){

                    int    temp = a[j];

                    a[j]=a[j+1];

                    a[j+1]=temp;

                }

            }

        }

        for(int i=0;i<a.length;i++){

            System.out.print(a[i]+" ");

        }

        System.out.println();

    }

    

}

结果是:

-96 -5 0 11 22 33 44 55 66 77 88 99

2、选择

package com.three;

public class Select {

    public static void main(String[] args) {

        int[] a= {77,99,44,55, 22, 88 ,11 ,0, 66,33 };

        myselect insert = new myselect(a);

        insert.sort();

    }

}

//选择排序

class myselect{

    private int[] a;

    public myselect(int[] a){

        this.a = a;

    }

    //选择排序

    public void sort(){

         for(int i=0;i<a.length;i++){

             int minindex = i;

             for(int j=i+1;j<a.length;j++){

                 if(a[j]<a[minindex]){

                     minindex = j;

                 }

             }

             int temp = a[i];

             a[i]=a[minindex];

             a[minindex]=temp;

         }

         //遍历

         for(int i=0;i<a.length;i++){

             System.out.print (a[i]+" ");

         }

         System.out.println();

    }

    

}

结果是:

0 11 22 33 44 55 66 77 88 99

3、插入

package com.three;

public class Insert {

    public static void main(String[] args) {

        int[] a= {77,99,44,55, 22, 88 ,11 ,0, 66,33 };

        myInsert insert = new myInsert(a);

        insert.sort();

    }

}

//插入排序

class myInsert{

    private int[] a;

    public myInsert(int[] a){

        this.a = a;

    }

    //排序方法

    public void sort(){

        for(int i=1;i<a.length;i++){

            int value = a[i];

            int valueIndex = i;

            

            while(valueIndex>0&&a[valueIndex-1]>=value){

                //将前边一位右移

                a[valueIndex] = a[valueIndex-1];

                //将前一位的位置空出来

                valueIndex--;

            }

            //将插入的值插入到空出来的那个位置

            a[valueIndex]= value;

        }

        //遍历

        for(int i=0;i<a.length;i++){

            System.out.print(a[i]+" ");

        }

        System.out.println();    

    }

}

结果是:

0 11 22 33 44 55 66 77 88 99
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: