Java实现双向冒泡排序

public class BubbleSort_Two {

public static void bubbleSort_Two(int[] list){
	//j在最外层定义
	boolean needNextPass = true;
	for(int i=0,j;i<list.length/2&&needNextPass;i++){
		needNextPass = false;
		//list.length-1-i 代替list.length-i(i初始化1)  保证反向冒泡
		for(j=i;j<list.length-1-i;j++){
			if(list[j]>list[j+1]){
				int temp = list[j];
				list[j] = list[j+1];
				list[j+1] = temp;
				needNextPass = true;
			}
		}
		System.out.println("-------------->第"+(i+1)+"次正向冒泡");
		//--j 遍历开始,j>i  外层循环i++保证了j的遍历结束也是不包含遍历过的
		for(--j;j>i;j--){
			if(list[j]<list[j-1]){
				int temp = list[j];
				list[j] = list[j-1];
				list[j-1] = temp;
				needNextPass = true;
			}
		}
		System.out.println("-------------->第"+(i+1)+"次反向冒泡");
	}
}
public static void main(String[] args) {
	int [] list = {2,3,2,5,6,1,-2,3,14,12};
	bubbleSort_Two(list);
	for(int i=0;i<list.length;i++){
		System.out.print(list[i]+" ");
	}

}

}

posted @ 2018-05-07 22:06  Loading~  阅读(405)  评论(0编辑  收藏  举报