冒泡排序

算法思想

     对要排序的数据,从上到下一次比较相邻的书并加以调整,将最大的数向下移动,较小的数向上冒起。即:每一趟一次比较相邻的两个元素,将较小的数放在左边,循环进行同样的操作,直到全部带排序的数据元素排完。

示例分析示意

    冒泡排序

代码实现

package test.algorithm.FastSlowPointer;

public class BubbleSort {
	
	/**
	 * 冒泡排序
	 * @param list
	 */
	public static void bubbleSort(int[] list){
		
		int temp = 0, count1=0, count2=0 ;
		
		//子序列是否无序(优化冒泡排序)
		boolean flag =true;
		
		//每一轮通过两两比较并判断是否移动,
		//一轮比较下来,即可获得最小元素
		for(int i=0;i<list.length && flag;i++){
			
			for(int j=list.length-1;j>i;j--){
				count1++;
				
				if(list[j-1]>list[j]){
					//移动元素即i之后子序列无序
					count2++;
					temp = list[j-1];
					list[j-1] = list[j];
					list[j] = temp;
					flag = true;
				}else{
					//不用移动元素即i之后子序列有序
					//i之后的元素不用比较
					flag = false;
				}
			}
		}
		System.out.println("比较"+count1+"次,移动"+count2+"次");
	}

	public static void main(String[] args) {
		int[] list = {5,2,6,0,3,9,1,7,4,8};
		bubbleSort(list);
		
		System.out.print("打印数组:");
		for(int i :list){
			System.out.print(i+" ");
		}
	}

}



你可能感兴趣的:(冒泡排序)