|
冒泡排序算法的一般性策略:搜索整個(gè)值列,比較相鄰元素,如果兩者的相對(duì)次序不對(duì),則交換它們,其結(jié)果是最大值“想水泡一樣”移動(dòng)到值列的最后一個(gè)位置上,這也是它在最終完成排序的值列中合適的位置。然后再次搜索值列,將第二大的值移動(dòng)至倒數(shù)第二個(gè)位置上,重復(fù)該過(guò)程,直至將所有元素移動(dòng)到正確的位置上。
下面是兩個(gè)Java冒泡算法程序:
public class Bubble {
// 冒泡排序函數(shù)1 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; } } } } // 冒泡排序函數(shù)2 public static int[] bubbleSort2(int[] m){ int intLenth = m.length; /*執(zhí)行intLenth次*/ for (int i=0;i<intLenth;i++){ /*每執(zhí)行一次,將最小的數(shù)排在后面*/ for (int j=0; j<intLenth-i-1;j++) { int a = m[j]; int b = m[j + 1]; if (a < b) { m[j] = b; m[j + 1] = a; } } } return m; } 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]); } } |
|
|
來(lái)自: software1 > 《java常用方法》