冒泡算法及其改进

import java.util.Arrays;

/** * Created by Niu on 16/11/28. */
public class BubbleSort {
    //版本A,最基本的冒泡排序算法
    public static void BubbleSort1(int[] a,int lo,int hi){
        int temp=0;
        for(int i=lo;i<hi;i++){ //这里的hi是哨兵,但lo是真实存在的
            for(int j=lo;j<hi-1-i;j++){
                if(a[j+1]<a[j]){
                    temp=a[j+1];
                    a[j+1]=a[j];
                    a[j]=temp;
                }
            }
        }
    }
    //版本B,进行改进,加入bool类型的标记,用来记录未就绪的元素是否已经是有序的
    public static void BubbleSort2(int[] a,int lo,int hi){
        boolean sorted=false;
        while(!sorted){
            sorted=true;
            for(int i=lo;i<hi-1;i++){
                if(a[i]>a[i+1]){
                    sorted=false;
                    int temp=a[i];
                    a[i]=a[i+1];
                    a[i+1]=temp;
                }
            }
        }
    }
    //版本C,进行步改进,加入Int类型,记录最后一次修改的秩的位置
    public static void BubbleSort3(int[] a,int lo,int hi){
        int last=hi;int n=last;
        for(int i=lo;i<hi;i++){
            for(int j=lo+1;j<last;j++){
                if(a[j-1]>a[j]){
                    int temp=a[j-1];
                    a[j-1]=a[j];
                    a[j]=temp;
                    n=j;
                }
            }
            last=n;
        }
    }
    //主进程
    public static void main(String[] args){
        int[] a={5,7,2,9,4,3,1};
        BubbleSort3(a,0,a.length);
        for(int k:a){
            System.out.print(k);
        }
    }
}

版本C描述起来比较费劲,详见:视频
参考博客:
1)http://blog.csdn.net/tjunxin/article/details/8711389
2)http://blog.csdn.net/u012152619/article/details/47305859

点赞