现在的位置: 首页 > 综合 > 正文

冒泡排序

2018年01月26日 ⁄ 综合 ⁄ 共 471字 ⁄ 字号 评论关闭
public class BubbleSort {

	public BubbleSort() {
	}

	/**
	 * 冒泡排序
	 * @param arr  排序前数组
	 * @return 排序后数组
	 */
	private int[] bubbleSort(int[] arr) {
		int i = arr.length;
		int j;
		while (i > 0) {
			for (j = 0; j < i - 1; j++) {// j:比较的次数
				if (arr[j] > arr[j + 1]) {
					int tmp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = tmp;
				}
			}
			i--;// 比较的组数
		}
		return arr;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] arr = { 1, 4, 10, 8, 3, 7, 0, 6, 5, 2, 9 };
		BubbleSort bsort = new BubbleSort();
		int[] a2 = bsort.bubbleSort(arr);
		for (int m = 0; m < a2.length; m++) {
			System.out.printf("%-4s", a2[m]);
		}
	}
}

抱歉!评论已关闭.