冒泡小演算法1,冒泡演算法1

來源:互聯網
上載者:User

冒泡小演算法1,冒泡演算法1

                                                                     冒泡小演算法1

  冒泡演算法:

例題.1

import java.util.*;
public class Nixun {
    public static void main(String[] args)
    {    
        System.out.println("一維數組逆序前的結果:");
        int a[]={9,8,7,6,5,4,3,2,1};
        Arrays.sort(a);
        for(int i=0;i<a.length;i++)
        {
            System.out.print(" "+a[i]);
        }
        }

    這個是調用了java.util.*;的工具包,用了Arrays.sort(a);方法即可,其中Arrays是數組的意思,而sort是排序,分類的意思。

要調用Arrays方法必須調用工具包才能用。

當然這個題還有其他的解法。

  解法二;

public class Nixun {
    public static void main(String[] args)
    {    
        System.out.println("一維數組逆序前的結果:");
        int a[]={9,8,7,6,5,4,3,2,1};
 
        for(int i=0;i<a.length;i++)
        {
            System.out.print(" "+a[i]);
        }
        
        
        System.out.println("之後的結果是:");
        for(int j=a.length-1;j>=0;j--)
        {
            System.out.print(" "+a[j]);
        }

    例題.2

public class A {
    public static void main(String[] args)
    {
         int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
         for(int i=0;i<score.length-1;i++)  //只需要比較 n-1次
         {
             for(int j=0;j<score.length-i-1;j++) //這裡是區間[0······ score.length-i-1]的值比較。
             {
                 if(score[j]<score[j+1])
                 {
                     int temp;
                     temp=score[j+1];
                     score[j+1]=score[j];
                     score[j]=temp;
                 }
             }
            

          }
          System.out.println("最終結果是:");
          for(int a=0;a<score.length;a++)
          {
               System.out.print(score[a]+"\t");
          }
    
 
}
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.