java中冒泡排序

冒泡排序

冒泡排序可以算是最经典的排序算法了,实现方法最简单,两层 for 循环,里层循环中判断相邻两个元素是否逆序,是的话将两个元素交换,外层循环一次,就能将数组中剩下的元素中最小的元素“浮”到最前面,所以称之为冒泡排序。

冒泡排序跟选择排序比较相像,比较次数一样,都为 n * (n + 1) / 2 ,但是冒泡排序在挑选最小值的过程中会进行额外的交换(冒泡排序在排序中只要发现相邻元素的顺序不对就会进行交换,与之对应的是选择排序,只会在内层循环比较结束之后根据情况决定是否进行交换)。

public static void main(String args[]) {
		int cost[] = { 1, 3, 15, 2, 6, 13, 9, 5, 14, 4, 7, 10, 11, 12, 8 };

		int swap;
		// 方法一:冒泡排序(小到大):面试常见的
		// 外层循环
		for (int i = (cost.length - 1); i >= 1; i--) {
			// 内层进行比较
			for (int j = 0; j < i; j++) {
				// 交换位置
				if (cost[j] > cost[j + 1]) {
					swap = cost[j];
					cost[j] = cost[j + 1];
					cost[j + 1] = swap;
				}
			}
		}

		// 打印测试结果
		for (int i = 0; i < cost.length; i++) {
			System.out.print(cost[i] + ",");
		}
		System.out.println();
		System.out.println("-----------");

		// 方法二:冒泡排序(小到大)
		for (int i = 1; i < cost.length; i++) {
			for (int j = 0; j < cost.length - i; j++) {
				if (cost[j] > cost[j + 1]) {
					swap = cost[j];
					cost[j] = cost[j + 1];
					cost[j + 1] = swap;

				}
			}
		}

		for (int i = 0; i < cost.length; i++) {
			System.out.print(cost[i] + ",");
		}
		System.out.println();
		System.out.println("------------");

		// 方法三:冒泡排序(小到大)
		for (int i = 0; i < cost.length; i++) {
			for (int j = 0; j < cost.length-i-1; j++) {  //-i让每一次比较的元素减少,-1避免越界
				if (cost[j] > cost[j + 1]) {
					swap = cost[j];
					cost[j] = cost[j + 1];
					cost[j + 1] = swap;

				}
			}
		}

		for (int i = 0; i < cost.length; i++) {
			System.out.print(cost[i] + ",");
		}
		System.out.println();
		System.out.println("------------");

		// 方法四:冒泡排序(小到大)
		for (int i = 0; i < cost.length; i++) {
			for (int j = i; j < cost.length; j++) {
				if (cost[i] > cost[j]) {
					swap = cost[i];
					cost[i] = cost[j];
					cost[j] = swap;

				}
			}
		}

		for (int i = 0; i < cost.length; i++) {
			System.out.print(cost[i] + ",");
		}
		System.out.println();
		System.out.println("------------");

		// 冒泡排序(大到小),只需要更改符号即可

		for (int i = 0; i < cost.length; i++) {
			for (int j = i; j < cost.length; j++) {
				if (cost[i] < cost[j]) {
					swap = cost[i];
					cost[i] = cost[j];
					cost[j] = swap;

				}
			}
		}

		for (int i = 0; i < cost.length; i++) {
			System.out.print(cost[i] + ",");
		}

	}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值