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);
	}

}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章