package com.yaoyuan; /** * 冒泡排序 * * 概述:冒泡排序算法的一般性策略:搜索整个值列,比较相邻元素,如果两者的相对次序不对, 则交换它们,其结果是最大值“想水泡一样”移动到值列的最后一个位置上, * 这也是它在最终完成排序的值列中合适的位置。然后再次搜索值列,将第二大的值移动至倒数第二个位置上, 重复该过程,直至将所有元素移动到正确的位置上。 * * @author *** * */ public class BubbleSort { /** * 冒泡1 * * @param data */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void bubbleSort1(Comparable[] data) { int position, scan; Comparable temp; for (position = data.length - 1; position >= 0; position--) { for (scan = 0; scan <= position - 1; scan++) { if (data[scan].compareTo(data[scan + 1]) < 0) { temp = data[scan]; data[scan] = data[scan + 1]; data[scan + 1] = temp; } } } } /** * 冒泡2 * * @param m * @return */ public static int[] bubbleSort2(int[] m) { int intLength = m.length; for (int i = 0; i < intLength; i++) { for (int j = 0; j < intLength - i - 1; j++) { int a = m[j]; int b = m[j + 1]; if (a < b) { m[j] = b; m[j + 1] = a; } } } return m; } /** * 冒泡2 * * @param args */ @SuppressWarnings("rawtypes") public static void main(String[] args) { // 冒泡排序1 Comparable[] c = { 4, 9, 23, 1, 45, 27, 5, 2 }; bubbleSort1(c); for (int i = 0; i < c.length; i++) System.out.println("冒泡排序1:" + c[i]); System.out.println("*******************"); // 冒泡排序2 int[] b = { 4, 9, 23, 1, 45, 27, 5, 2 }; int[] e = bubbleSort2(b); for (int j = 0; j < e.length; j++) System.out.println("冒泡排序2:" + e[j]); } }