serie de Java tipo ordinario, la burbuja básica especie, burbuja especie de distinción y optimizar la prueba

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

}

Aquí Insertar imagen Descripción

Publicado 37 artículos originales · ganado elogios 29 · Vistas a 10000 +

Supongo que te gusta

Origin blog.csdn.net/qq_42755868/article/details/105030403
Recomendado
Clasificación