Java数列普通排序,基本冒泡排序,优化冒泡排序的区分和测试

import java.util.Arrays;
public class TestBubbleSort {
	public static void main(String[] args) {
		int[] array = { 3, 1, 6, 2, 9, 0, 7, 4, 5, 8 };//普通排序45次比对
		NotbubbleSort(array);
		System.out.println(Arrays.toString(array));
		int[] array2 = { 3, 1, 6, 2, 9, 0, 7, 4, 5, 8 };//普通冒泡45次
		bubbleSortBase(array2);
		System.out.println(Arrays.toString(array2));
		int[] array3 = { 3, 1, 6, 2, 9, 0, 7, 4, 5, 8 };//优化冒泡39次
		bubbleSortBetter(array3);
		System.out.println(Arrays.toString(array3));
		int[] array4 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};//优化的冒泡最少可以比较array.length-1次
		bubbleSortBetter(array4);
		System.out.println(Arrays.toString(array4));
	}
	private static void NotbubbleSort(int[] array) {//普通的逐一比对
		int count = 0;
		int temp;
		for (int i = 0; i < array.length; i++) {
			for (int j = i+1; j < array.length; j++) {
				count++;
				temp = array[i];
				if(array[i]>array[j]) {
					array[i] = array[j];
					array[j] = temp;
				}
			}
		}
		System.out.println(count);
	}
	private static void bubbleSortBase(int[] array) {//基本的冒泡
		int count = 0;
		int temp;
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array.length-i-1; j++) {
				count++;
				if(array[j]>array[j+1]) {
					temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
		System.out.println(count);
	}
	private static void bubbleSortBetter(int[] array) {//优化的冒泡
		int count = 0;
		int temp;
		for (int i = 0; i < array.length-1/*去除最后一个数,此外肯定不会进入下方的循环的*/; i++) {
			boolean isSorted = true;
			for (int j = 0; j < array.length-i-1; j++) {
				count++;
				if(array[j]>array[j+1]) {
					temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
					isSorted = false;//当前数列大小关系还不完美
				}
			}
			if(isSorted) {
				break;
			}
		}
		System.out.println(count);
	}

}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值