Java终极冒泡排序

// 冒泡排序
	public static void bubble(int[] a) {
		int count = 0;// 统计循环次数
		boolean isOk = true;// 标志位
		for (int i = 0; i < a.length; i++) {// 再好一点点的细节,a.length外提,编译原理中优化的一种:循环量外提
			/*或者可以
			for (int i = a.length; i > 0; --i) {
				for (int j = 0; j < i; ++j) {
				}
			}*/
			for (int j = 0; j < a.length - i - 1; ++j) {
				if (a[j] > a[j + 1]) {//可以这样交换两个数字,效率很高,当然更重要的是看起来很能装~
					a[j] ^= a[j + 1];
					a[j+1] ^= a[j];
					a[j] ^= a[j+1];
					isOk = false;// 一趟有交换,则说明未排好
				}
				++count;
			}
			if (isOk)// 排好则不继续比较
				break;
		}
		System.out.println(count);
	}

	public static void main(String[] args) {
		// 测试已经排好序的比较次数
		int a[] = { 1, 1, 1, 2, 3, 32, 45, 49, 61 };
		bubble(a);
		System.out.println(Arrays.toString(a));
                
		int b[] = { 1111, 111, 111, 92, 90, 32, 40, 9, 6, 1 };
		bubble(b);
		System.out.println(Arrays.toString(b));
	}
所有文章未特殊说明均属原创,有误之处欢迎提出,转载随意,您喜欢就好,但请注明,谢谢!
原文地址:https://www.cnblogs.com/nonefly/p/4762224.html