基础冒泡排序

import java.util.Arrays;

/**
 * This program demonstrates bubble sort. 冒泡排序的实现方式及优化,个人练习,如有错误请大侠指出
 */

public class BubbleSortImpro {

	public static void main(String[] args) {
		int[] a = { 3, 5, 10, 4, 1 };
		bubbleSort1(a);
		System.out.println("The 1 result: " + Arrays.toString(a));

		int[] b = { 3, 5, 10, 4, 1 };
		bubbleSort2(b);
		System.out.println("The 2 result: " + Arrays.toString(b));

		int[] c = { 3, 5, 10, 4, 1 };
		bubbleSort3(c);
		System.out.println("The 3 result: " + Arrays.toString(c));
	}

	// 第一种实现:(前两种实现都是稳定排序)
	private static void bubbleSort1(int[] arr) {
		for (int i = 0; i < arr.length - 1; i++)
			for (int j = 0; j < arr.length - 1 - i; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = 0;
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
	}

	// 第二种实现:
	private static void bubbleSort2(int[] arr) {
		for (int i = arr.length - 1; i > 0; --i)
			for (int j = 0; j < i; ++j) {
				if (arr[j] > arr[j + 1]) {
					int temp = 0;
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
	}

	// 第三种实现;省略了中间的多次交换,这种实现使冒泡排序变成了不稳定排序(参考来的....)
	private static void bubbleSort3(int[] arr) {
		for (int i = arr.length - 1, max = 0; i > 0; max = 0, --i) {
			for (int j = 1; j < i; ++j) {
				if (arr[j] > arr[max])
					max = j;
			}
			if (arr[max] > arr[i]) {
				int temp = 0;
				temp = arr[max];
				arr[max] = arr[i];
				arr[i] = temp;
			}
		}
	}
}

Java初学者



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值