Java实现各类排序

来源:互联网 发布:淘宝信用卡哪个好 编辑:程序博客网 时间:2024/05/01 19:22
<span style="font-size:18px;"> //冒泡排序    void bubble(int[] A){        boolean flag=true;        for(int i=0;i<A.length-1;i++){            for(int j=0;j<A.length-1-i;j++){                if(A[j]>A[j+1]){                    int temp=A[j+1];                    A[j+1]=A[j];                    A[j]=temp;                    flag=false;                }            }            if(flag)break;        }    }</span>


<span style="font-size:18px;">//插入排序    void insert(int[] A){        for(int i=0;i<A.length-1;i++){            for(int j=i+1;j>0;j--){                if(A[j]<A[j-1]){                    int temp=A[j];                    A[j]=A[j-1];                    A[j-1]=temp;                }            }        }    }</span>

<span style="font-size:18px;"> //选择排序    void select(int[] A){        for(int i=0;i<A.length-1;i++){            for(int j=i+1;j<A.length;j++){                if(A[j]<A[i]){                    int temp=A[j];                    A[j]=A[i];                    A[i]=temp;                }            }        }    }</span>

<span style="font-size:18px;">//快速排序    void quick(int[]A,int begin,int end){        if(begin<end){            int mid=getMid(A,begin,end);            quick(A,begin,mid-1);            quick(A,mid+1,end);        }    }    int getMid(int[]A,int begin,int end){        int temp=A[begin];        while(begin<end){            while (begin<end&&A[end]>=temp){                end--;            }            A[begin]=A[end];            while(begin<end&&A[begin]<temp){                begin++;            }            A[end]=A[begin];        }        A[begin]=temp;        return begin;    }</span>

<span style="font-size:18px;"> //堆排序    void heap(int[] A){        for(int i=A.length/2-1;i>=0;i--){            construction(A,i,A.length);        }        for(int i=A.length-1;i>0;i--){            int temp=A[0];            A[0]=A[i];            A[i]=temp;            construction(A,0,i);        }    }    void construction(int[] A,int index,int max){        int left=index*2+1;        int right=index*2+2;        int large=0;        if(left<max&&A[left]>A[index]){            large=left;        }else {            large=index;        }        if(right<max&&A[right]>A[large]){            large=right;        }        if(large!=index){            int temp=A[large];            A[large]=A[index];            A[index]=temp;            construction(A,large,max);        }    }</span>


0 0
原创粉丝点击