电竞比分网-中国电竞赛事及体育赛事平台

分享

Java 冒泡排序算法

 software1 2011-09-06
冒泡排序算法的一般性策略:搜索整個(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]);    
    }
}

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多