Java实现冒泡排序

Java实现冒泡排序

  • 介绍
    冒泡排序可以说是排序中几位简单基础的一种了,其复杂度为N的平方,最坏的情况就是吧一个顺序的排成倒序的今天说一个优化的小细节
  • 实现过程
package bubblesort;

public class Demo {
	public static void main(String[] args) {
		System.out.println("第一组随机数");
		int []a = new int [15];
		for (int i = 0; i< a.length ; i++) {
			a[i] = (int)(Math.random()*100);
		}
		for (int i : a) {
			System.out.print(i+" ");
		}	
		bubblesort(a);
		System.out.println();
		System.out.println("传统的方法交换后");
		for (int i : a) {
			System.out.print(i+" ");
		}		
		
		
		System.out.println();
		System.out.println("第二组随机数");
		int []b = new int [15];
		for (int i = 0; i< b.length ; i++) {
			b[i] = (int)(Math.random()*100);
		}
		for (int i : b) {
			System.out.print(i+" ");
		}
	
		butterbubblesort(b);
		System.out.println();
		System.out.println("更新后的方法交换后");
		for (int i : b) {
			System.out.print(i+" ");
		}	
	}
	static void bubblesort(int [] a) {
		int temp;
		for(int i = a.length-1 ; i>=0 ; i--) {
			for(int j = 0 ; j < i;j++) {
				if(a[j]>a[j+1]) {
				//以下三行为核心代码
					temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp;
				}
			}
		}
	}
	static void butterbubblesort(int [] a) {
		int temp;
		boolean exchage = false;
		for(int i = a.length-1 ; i>=0 ; i--) {
			for(int j = 0 ; j < i;j++) {
				if(a[j]>a[j+1]) {
				//以下四行为核心代码
					temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp;
					//这新增的优化细节,用于判断数组是否已经顺序
					exchage = true;
				}
			}
			if(!exchage) {
				return;
			}
		}
	}
}

  • 运行结果
    Java实现冒泡排序

  • 虽然很简单基础但是复杂的东西都是从基础演变而来的,切勿好高骛远