爱程序网

冒泡小算法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");
          }
    
 
}
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助