冒泡排序

冒泡排序是一种简单的交换排序,其原理是对排序对象从头到尾进行扫描,并对相邻两个元素做比较,数值大的往后移。

一般的,对n个元素进行冒泡排序,总共需要进行n-1趟。第一趟需要比较n-1次,第二趟需要比较n-2次,......,第n趟需要比较n-i次

算法实现:

public class BubbleSort {
	
	public static void main(String[] args){
		int[] content = new int[]{12,100,86,6,7};
		System.out.println(Arrays.toString(content));
		bubbleSort(content);
		System.out.println(Arrays.toString(content));
		
	}
	
	public  static void bubbleSort(int[] content){
		int len = content.length;
		int temp;
		for(int i = 0; i < len; i++ ){//多少趟
			
			for(int j = 0; j < len - i -1 ; j++){//比较次数
				
				if(content[j] > content[j+1]){
					temp = content[j];
					content[j] = content[j+1];
					content[j+1] = temp;
				}
			}
		}
	}
}

  

原文地址:https://www.cnblogs.com/shindo/p/5550785.html