Java的排序算法之冒泡排序

标题:Java的排序算法之冒泡排序

一、原理
迭代n-1次,每一次都将【0–>n-1-i】中最大的元素迭代到最后面去,

对于这样的数组{32,15,6,48,19,21,2}

即第一次遍历0-->n-1;{32,15,6,48,19,21,2},排序后为{15,6,32,19,21,2,48}
第二次遍历第二次排序后的【即不需遍历48】0->n-2;{15,6,32,19,21,2},排序后为{6,15,19,21,2,32,48}

核心代码如下:

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];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
			}
		}

二、优化;
冒泡排序总共n-1趟,若有一趟不需要交换,则说明已经排好序了,如下:

for(int i=0;i<a.length-1;i++) {
			boolean flag=false;
			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;
					flag=true;
				}
			}
			if(!flag) {//冒泡排序总共n-1趟,若有一趟不需要交换,则说明已经排好序了,
				return a;
			}
		}

完整代码如下:

/**
 * 测试冒泡排序
 * @author dell
 *
 */
public class TestBubbleSort {
	/**
	 * 冒泡排序
	 * @param a
	 * @return
	 */
	public int[] bubbleSort(int[] a) {
		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];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
			}
		}
		return a;
	}
	@Test
	public void test() {
		int[] a=new int[] {32,15,6,48,19,21,2};
//		int[] a=new int[] {43,12,35,18,26,57,7,21,43,46};
		a=this.bubbleSort(a);
		for(int in:a) {
			System.out.print(in+" ");
		}
	}
	
	/**
	 * 冒泡排序的【优化】
	 * @param a
	 * @return
	 */
	public int[] bubbleSort02(int[] a) {
		for(int i=0;i<a.length-1;i++) {
			boolean flag=false;
			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;
					flag=true;
				}
			}
			if(!flag) {//冒泡排序总共n-1趟,若有一趟不需要交换,则说明已经排好序了,
				return a;
			}
		}
		return a;
	}
	@Test
	public void test02() {
		int[] a=new int[] {32,15,6,48,19,21,2};
//		int[] a=new int[] {43,12,35,18,26,57,7,21,43,46};
		a=this.bubbleSort02(a);
		for(int in:a) {
			System.out.print(in+" ");
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值