優化冒泡排序

普通的冒泡排序:

import java.util.Arrays;

public class BubbleSort {
	public static void main(String[] args) {
		int a[] = { 4, 9, 2, 1, 6, 7, 8, 3, 10 };
		int temp = 0;
		int n = 0;
		for (int i = 0; i < a.length - 1; i++) {
			for (int j = 0; j < a.length - 1 - i; j++) {
				if (a[j] > a[j + 1]) {
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
				}
				n++;
			}
		}
		System.out.println(Arrays.toString(a));
		System.out.println("迭代次數:" + n);
	}
}

結果:

[1, 2, 3, 4, 6, 7, 8, 9, 10]
迭代次數:36

優化後的冒泡排序:

import java.util.Arrays;

public class BubbleSort {
	public static void main(String[] args) {
		int a[] = { 4, 9, 2, 1, 6, 7, 8, 3, 10 };
		int temp = 0;
		int n=0;
		for (int i = 0; i < a.length - 1; i++) {
			boolean flag=true;
			for (int j = 0; j < a.length - 1 - i; j++) {
				if (a[j] > a[j + 1]) {
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
					flag=false;
				}
				n++;
			}
			if(flag) {
				break;
			}
		}
		System.out.println(Arrays.toString(a));
		System.out.println("迭代次數:"+n);
	}
}

結果:

[1, 2, 3, 4, 6, 7, 8, 9, 10]
迭代次數:33
 

發佈了135 篇原創文章 · 獲贊 76 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章