Java BubbleSort

package sort.bubble;

import java.util.Arrays;

public class BubbleSort {

	public static void main(String[] args) {
		int[] arr = {6,8,4,7,9,12};
		
		bubbleSort(arr);
		//bubbleSort2(arr);
		//bubbleSort1(arr);
	}
	
	/*交换次数最少的冒泡排序
	 * 冒泡排序,根据最后交换数位置
	 */
	public static void bubbleSort(int[] arr)
	{
		int start = 0;				//未排序数组开始位置
		int end =arr.length; 		    //未排序数组结束位置
		int current;				//未排序数组当前位置
		int last;				//未排序数组最后一次发生交换的位置
		
		while(start <end)
		{
			current = last = start;
			while(++current <end)
			{
				if(arr[current] < arr[current-1])
				{
					last = current;					//当前位置发生交换,记录改变位置
					int temp = arr[current];
					arr[current]= arr[current -1];
					arr[current-1] = temp;
				}
				System.out.println(Arrays.toString(arr));
			}
			
			end = last;			
			System.out.println("--"+Arrays.toString(arr) +"  " +last);
		}
		System.out.println("@@ "+Arrays.toString(arr));
	}
	
	public static void bubbleSort1(int[] arr)
	{
		int len = arr.length -1;
		
		for(int i =0;i<len;i++)
		{
			for(int j= i+1;j<len+1;j++)
			{
				if(arr[i] < arr[j])
				{
					int temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
				System.out.println(Arrays.toString(arr));
			}
			System.out.println("-----"+Arrays.toString(arr));
		}
		
	}
	
	//第二版本,减少每一趟的次数
	public static void bubbleSort2(int[] arr){
			boolean sorted= true;
			int len =arr.length;
			for(int j=0;j<len-1;j++){ //趟数
				sorted =true; //假定有序
				for(int i=0;i<len-1-j;i++){ //次数
					if(arr[i]>arr[i+1]){
						int temp = arr[i];
						arr[i] =arr[i+1];
						arr[i+1] =temp;
						sorted =false; //假定失败
					}
					System.out.println(Arrays.toString(arr));
				}
				if(sorted){ //减少趟数
					break;
				}
				System.out.println("-----"+Arrays.toString(arr));
			}
			
		}
		
}

  

转载于:https://www.cnblogs.com/fancyzhen/p/4022593.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值