标签:
冒泡排序 最佳时间复杂度O(n),最差时间复杂度O(n2)
public class BubbleSort { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] a = { 2, 3, 2, 5, 6, 1, -2, 3, 14, 12 }; bubbleSort2(a); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } private static void bubbleSort(int[] a) { boolean needNextPass = true; for (int i = 1; i < a.length && needNextPass; i++) { // Array may be sorted and next pass not needed needNextPass = false; for (int j = 0; j < a.length - i; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; needNextPass = true; } } } } private static void bubbleSort2(int[] a) { boolean needNextPass = true; for (int i = a.length - 1; i > 0 && needNextPass; i--) { // Array may be sorted and next pass not needed needNextPass = false; for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; needNextPass = true; } } } } }
标签:
原文地址:http://www.cnblogs.com/diyishijian/p/5080062.html